[LeetCode] 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
.
顺序扫描一遍即可,注意释放被删除的结点的空间。
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == NULL) return NULL; ListNode *last = head, *current = head -> next, *tmp = NULL; while(current != NULL) { while(current != NULL && current -> val == last -> val) { tmp = current; current = current -> next; delete tmp; } last -> next = current; last = current; if(current != NULL) current = current -> next; } return head; } };