[LeetCode] Remove Duplicates from Sorted List

时间:2023-03-08 17:50:01

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.

这题比较简单,用两个指针,一个cursor遍历链表用,一个stick指向上一个不重复的node,这样每次遍历时如果cursor跟stick不一样的话就把stick的next指向cursor,然后更新stick,这样一直到遍历结束,还有最后一步很容易遗漏,就是把stick指向NULL,因为此时stick应该是新链表的尾巴。

这个方法能适用是因为链表是有序的。

ListNode *deleteDuplicates(ListNode *head) {
if (!head) return NULL; ListNode *stick = head, *cursor = head->next;
while (cursor) {
if (cursor->val == stick->val) {
cursor = cursor->next;
continue;
}
else {
stick->next = cursor;
stick = cursor;
}
cursor = cursor->next;
}
stick->next = NULL;
return head;
}