Leetcode: remove duplicates from sorted list
Given a sorted Linked List, delete all duplicates such that each element appear onlyOnce.
For example,
Given1->1->2, Return1->2.
Given1->1->2->3->3, Return1->2->3.
Address: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
Algorithm: No problem. Check the Code directly:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 ListNode *deleteDuplicates(ListNode *head) {12 if(!head || head->next == NULL) return head;13 ListNode *p = head;14 while(p->next){15 if(p->next->val == p->val){16 ListNode *q = p->next;17 p->next = q->next;18 free(q);19 }else{20 p = p->next;21 }22 }23 return head;24 }25 };
Question 2:
Given a sorted Linked List, delete all nodes that have duplicate numbers, leaving onlyDistinctNumbers from the original list.
For example,
Given1->2->3->3->4->4->5, Return1->2->5.
Given1->1->1->2->3, Return2->3.
Address: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Algorithm: This question is a little more difficult than the above question, but it is not very difficult. Code:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 ListNode *deleteDuplicates(ListNode *head) {12 if(!head || head->next == NULL) return head;13 ListNode *pre = NULL;14 ListNode *p = head;15 while(p){16 ListNode *q = p->next;17 while(q && q->val == p->val){18 q = q->next;19 }20 if(p->next == q){21 pre = p;22 p = p->next;23 }else{24 if(pre){25 pre->next = q;26 }else{27 head = q;28 }29 while(p != q){30 ListNode *tempP = p->next;31 free(p);32 p = tempP;33 }34 p = q;35 }36 }37 return head;38 }39 };
Leetcode: remove duplicates from sorted list