题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
题解:
Solution 1 ()
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { ListNode* cur = head; while (cur != nullptr && cur->next != nullptr) { if (cur->val == cur->next->val) { cur->next = cur->next->next; continue; } cur = cur->next; } return head; } };
Solution 2 ()
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(!head || !head->next) return head; ListNode *front, *last; front = head; last = head->next; while(last) { if(front->val == last->val) { front->next = last->next; delete last; last = front->next; } else { front = last; last = last->next; } } return head; } };