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
.
Have you met this question in a real interview?
Yes
No
思路:和Remove Duplicates from Sorted List一样,双指针,head指向要插入node的前一个node,p指向当前处理的node。
如何判断是否重复呢,判断p和p->next是否一样,若一样,则不插入,不一样就要插入,但是这里忽略了NULL的处理,如果p->next== NULL,要单独处理。。
另外,在找到p->val == p->next->val 时,要找打下一个p,不等于之前的val。
/** * 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) { if(head == NULL) return NULL; ListNode * p = head; ListNode dummy(-1); head = &dummy; while(p) { if(p->next == NULL || p->val != p->next->val) { head->next = p; head = p; p = p->next; // to break old link head->next = NULL; } else { //find the node which its value is not equla to p->val // and store the node as new p; p = p->next; while(p) { if(p->next == NULL) { //should end head->next = NULL; p = NULL;// jump the outer loop break;// jump the inner loop } if(p->val != p->next->val) { p = p->next; break; } else p = p->next; } } #if 0 cout << "p->val " << p->val << endl; cout << "head->val " << head->val << endl; #endif } return dummy.next; } };