* Problem:
* Given a sorted linked list, delete all nodes that have duplicate numbers
* leaving only distinct numbers from the original list.
* Solution:
* Compare the current position with the previous and behind it. If it does not equal to them, then we add it to the
* new List.
* What to learn:
* Beware that if the list is NULL or there are only one item in the list, they are specific situation.
* Another good solution:
* Add a dummy node before the head, and to check if the node is first one that duplicate with others, if it does, then
* at the following step, delete it. Remember to delete the unused item if you really want to delete it.
* To refer : http://bangbingsyb.blogspot.com/2014/11/leetcode-remove-duplicates-from-sorted_19.html
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
注意要点:
II比I难在需要删除所有的重复节点。这里需要注意两点:
一定要注意去掉最开始为空的一些特殊情况。 然后学会使用 delete 删掉节点。
1. 头节点也可能被删除。可以使用dummy节点来简化。
2. 如果采用与I类似的思路来删除当前节点后所有的重复节点,则完成后还需要把当前节点也删除。因此需要有一个变量来记录当前节点是否有重复。
参考 : http://bangbingsyb.blogspot.com/2014/11/leetcode-remove-duplicates-from-sorted_19.html
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 6 struct ListNode { 7 int val; 8 ListNode *next; 9 ListNode(int x) : val(x), next(NULL) {} 10 }; 11 12 void print(ListNode *l) 13 { 14 ListNode *head = l; 15 while(head!=NULL) 16 { 17 cout<< head->val<<endl; 18 head = head-> next; 19 } 20 } 21 22 23 class Solution { 24 public: 25 ListNode *deleteDuplicates(ListNode *head) { 26 if(head == NULL) 27 return NULL; 28 if(head->next == NULL) 29 return head; 30 31 int flag = 0; 32 ListNode * newhead,* p, *pre; 33 newhead = p = pre = head; 34 int prevalue = p->val; 35 36 while(p!=NULL) 37 { 38 if((p!=newhead && prevalue==p->val)||( p->next!=NULL && p->val==p->next->val)) // consider the regular situation. 39 { 40 prevalue = p->val; 41 p = p->next; 42 43 } 44 else 45 { 46 if(flag == 0) // consider the newhead. 47 newhead = p; 48 flag = 1; 49 prevalue = p->val; 50 if(p != head) 51 { 52 pre -> next = p; 53 pre = pre->next; 54 } 55 56 p = p->next; 57 } 58 59 } 60 if(flag == 0) 61 return NULL; 62 pre ->next = NULL; 63 delete(p); 64 return newhead; 65 } 66 }; 67 68 ListNode* create_list(int* array,int n) 69 { 70 if (n==0) 71 return NULL; 72 ListNode *head,*current; 73 head = current = new ListNode(array[0]); 74 for (int i=1;i<n;i++) 75 { 76 ListNode *node = new ListNode(array[i]); 77 current -> next = node; 78 current = current -> next; 79 } 80 return head; 81 } 82 83 84 int main() 85 { 86 //vector <int> a = {1,3,5}; 87 Solution ans; 88 //int a[3] = {1,3,5}; 89 int b[2] = {1,1}; 90 ListNode * first = create_list(b,2); 91 //ListNode * second = create_list(a,3); 92 ListNode * pure = ans.deleteDuplicates(first); 93 if(pure == NULL) 94 printf("NULL"); 95 else 96 print(pure); 97 return 0; 98 }