給定一個排序鏈表,刪除所有含有重復(fù)數(shù)字的節(jié)點,只保留原始鏈表中 沒有重復(fù)出現(xiàn) 的數(shù)字。
示例 1:
輸入: 1->2->3->3->4->4->5
輸出: 1->2->5
示例 2:
輸入: 1->1->1->2->3
輸出: 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) {
if (!head || !head->next) return head;
ListNode *start = new ListNode(0);
start->next = head;
ListNode *pre = start;
while (pre->next) {
ListNode *cur = pre->next;
while (cur->next && cur->next->val == cur->val) cur = cur->next;
if (cur != pre->next) pre->next = cur->next;
else pre = pre->next;
}
return start->next;
}
};