我承认我链表真是一塌糊涂……
/**
* 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 || head->next == NULL)
return head;
ListNode *last = head, *p = head->next;
last->next = NULL;
while (p != NULL) {
if (p->val == last->val)
p = p->next;
else {
last->next = p;
last = p;
p = p->next;
last->next = NULL;
}
}
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) {
ListNode *pre,*now;
if(!head||!head->next)return head;
pre=head;
now=head->next;
while(now)
{
if(pre->val==now->val)
{
pre->next=now->next;
now=now->next;
}
else
{
pre=now;
now=now->next;
}
}
return head;
}
};
// blog.youkuaiyun.com/havenoidea
http://blog.youkuaiyun.com/havenoidea/article/details/12883023
http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/