Remove Duplicates from Sorted List II Solutions in C++
Number 82
Difficulty Medium
Acceptance 36.9%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/// Author : Hao Chen// Date : 2014-06-25#include <stdio.h>struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *deleteDuplicates(ListNode *head) {ListNode fake(-1);fake.next = head;head = &fake;ListNode *tail=head;bool dup = false;for(ListNode *p=head->next; p && p->next; p=p->next){if (dup==false && p->val == p->next->val){dup = true;continue;}if (dup==true && p->val != p->next->val){dup = false;tail->next = p->next;continue;}if (dup==false){tail = p;}}if (dup==true){tail->next = NULL;}return head->next;}void printList(ListNode* h){while(h!=NULL){printf("%d ", h->val);h = h->next;}printf("\n");}ListNode* createList(int a[], int n){ListNode *head=NULL, *p=NULL;for(int i=0; i<n; i++){if (head == NULL){head = p = new ListNode(a[i]);}else{p->next = new ListNode(a[i]);p = p->next;}}return head;}int main(){int a[]={1,1,2,3,3};int b[]={1,1,1};int c[]={1,2,3};int d[]={3};printList(deleteDuplicates(createList(a, sizeof(a)/sizeof(int))));printList(deleteDuplicates(createList(b, sizeof(b)/sizeof(int))));printList(deleteDuplicates(createList(c, sizeof(c)/sizeof(int))));printList(deleteDuplicates(createList(d, sizeof(d)/sizeof(int))));return 0;}
C++ solution by pezy/LeetCode
#include <cstddef>struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {public:ListNode *deleteDuplicates(ListNode *head) {if (head == NULL) return head;ListNode preHead(0);preHead.next = head;ListNode *pre = &preHead;bool isDuplicate = false;ListNode *p = head;while (p->next)if (p->val == p->next->val) {ListNode *next = p->next->next;delete p->next;p->next = next;isDuplicate = true;} else if (isDuplicate) {ListNode *next = p->next;delete p;p = next;pre->next = p;isDuplicate = false;} else {pre = p;p = p->next;}if (isDuplicate) {ListNode *next = p->next;delete p;pre->next = next;}return preHead.next;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii//// Author : liuyubobobo/// Time : 2019-02-11#include <iostream>using namespace std;/// Linear Scan/// Time Complexity: O(n)/// Space Complexity: O(1)/// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {public:ListNode* deleteDuplicates(ListNode* head) {ListNode* dummyHead = new ListNode(-1);dummyHead->next = head;ListNode* prev = dummyHead;ListNode* cur = prev->next;while(cur){int num = 0;ListNode* p = cur;while(p && p->val == cur->val){num ++;p = p->next;}if(num > 1)prev->next = p;elseprev = cur;cur = p;}ListNode* ret = dummyHead->next;delete dummyHead;return ret;}};int main() {return 0;}