Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->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 *pre = head, *cur = head->next;
while (cur) {
if (pre->val == cur->val) {
pre->next = cur->next;
delete(cur);
cur = cur->next;
}
else {
pre = cur;
cur = cur->next;
}
}
return head;
}
};