Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if(head == NULL || head->next == NULL) return head; int curVal = head->val; // P指向已经处理的合法listNode 的最后一个Node //q 指向当前政要处理的节点 ListNode *p = NULL,*q = head, *temp; head = NULL ; bool needDelete = false ; while(q) { if(needDelete == false){ if(q->next && q->next->val == q->val){ curVal = q->val; needDelete = true; temp = q->next->next; delete q->next; delete q; q = temp; }else{ if(head == NULL) { head = q; p = q; }else{ p->next = q; p = q; } q = q->next; } }else{ // else of needDelete = true if(q->val == curVal) { temp = q->next; delete q; q = temp; }else{ needDelete =false; } } } if(p) p->next = NULL; return head ; } };
重写: 加了个虚拟根节点,从然使得自己从边界中解放出来
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if(head == NULL || head ->next == NULL) return head; ListNode * head0, *cur; head0 = new ListNode(0); head0->next = head; head = head0; cur = head0; while(cur->next != NULL){ ListNode * p = cur->next; ListNode *temp; while(p->next != NULL && p->next->val == p->val) { temp = p; p = p->next; delete temp; } if(p == cur->next){ cur = cur->next; }else{ cur->next = p->next; delete p; } } return head->next; } };