Remove Duplicates from Sorted List
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
.
分析: two pointers,pre_p 和 p, 注意删除p与不删除p,pre_p与pre_p->next的更新。
代码:
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(head == NULL || head->next == NULL) return head; for(ListNode * pre_p = head, * p = head->next; p != NULL; p = p->next){ if(pre_p->val == p->val){ pre_p->next = p->next; }else{ pre_p = pre_p->next; } } return head; } };