題目
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) {
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;
}
};
分析
和之前那道Remove Duplicates from Sorted List不同的地方是這里要?jiǎng)h掉所有的重復(fù)項(xiàng),由于鏈表開頭可能會(huì)有重復(fù)項(xiàng),被刪掉的話頭指針會(huì)改變,而最終卻還需要返回鏈表的頭指針。所以需要定義一個(gè)新的節(jié)點(diǎn),然后鏈上原鏈表,然后定義一個(gè)前驅(qū)指針和一個(gè)現(xiàn)指針,每當(dāng)前驅(qū)指針指向新建的節(jié)點(diǎn),現(xiàn)指針從下一個(gè)位置開始往下遍歷,遇到相同的則繼續(xù)往下,直到遇到不同項(xiàng)時(shí),把前驅(qū)指針的next指向下面那個(gè)不同的元素。如果現(xiàn)指針遍歷的第一個(gè)元素就不相同,則把前驅(qū)指針向下移一位。