題目
給定一個(gè)排序鏈表,刪除所有含有重復(fù)數(shù)字的節(jié)點(diǎn),只保留原始鏈表中 沒(méi)有重復(fù)出現(xiàn) 的數(shù)字。
示例 1:
輸入: 1->2->3->3->4->4->5
輸出: 1->2->5
示例 2:
輸入: 1->1->1->2->3
輸出: 2->3
思路
和之前那道83.刪除排序鏈表中的重復(fù)元素不同的地方是這里要?jiǎng)h掉所有的重復(fù)項(xiàng),由于鏈表開(kāi)頭可能會(huì)有重復(fù)項(xiàng),被刪掉的話頭指針會(huì)改變,而最終卻還需要返回鏈表的頭指針。所以需要定義一個(gè)新的節(jié)點(diǎn),然后鏈上原鏈表,然后定義一個(gè)前驅(qū)指針和一個(gè)現(xiàn)指針,每當(dāng)前驅(qū)指針指向新建的節(jié)點(diǎn),現(xiàn)指針從下一個(gè)位置開(kāi)始往下遍歷,遇到相同的則繼續(xù)往下,直到遇到不同項(xiàng)時(shí),把前驅(qū)指針的next指向下面那個(gè)不同的元素。如果現(xiàn)指針遍歷的第一個(gè)元素就不相同,則把前驅(qū)指針向下移一位。
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL) 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;
}
cur != pre->next ? pre->next = cur->next : pre = pre->next;
}
return start->next;
}
};