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) return head;
ListNode* cur = new ListNode(0);
cur->next = head;
head = cur;
cur = cur->next;
ListNode* pre = cur->next;
ListNode* pos = head;
bool del = false;
while(pre != NULL)
{
if (pre->val == cur->val)
{
del = true;
ListNode* tmp = pre;
pre = pre->next;
cur->next = pre;
delete tmp;
}
else
{
if (del)
{
del = false;
delete cur;
pos->next = pre;
cur = pre;
pre = pre->next;
}
else
{
pos = cur;
cur = pre;
pre = pre->next;
}
}
}
if (del)
{
del = false;
delete cur;
pos->next = NULL;
}
cur = head;
head = head->next;
delete cur;
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) return NULL;
ListNode* pre = head;
ListNode* cur = NULL;
while(pre != NULL)
{
if (pre->next == NULL || pre->val != pre->next->val)
{
if(cur == NULL)
cur = head;
else
cur = cur->next;
cur->val = pre->val;
}
else
{
while(pre->next != NULL && pre->val == pre->next->val)
{
pre = pre->next;
}
}
pre = pre->next;
}
if (cur == NULL)
head = NULL;
else
cur->next = NULL;
return head;
}
};