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.
Classical Two pointers method to Linked List.
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;
ListNode* newHead = head;
ListNode* slow = head;
ListNode* fast = head->next;
while(fast) {
if(slow->val != fast->val) {
slow->next = fast;
slow = fast;
fast = fast->next;
} else {
fast = fast->next;
}
}
slow->next = NULL;
return newHead;
}
本文介绍了一种使用双指针法从已排序链表中移除所有重复元素的方法,确保每个元素只出现一次。提供了完整的C++代码实现。
728

被折叠的 条评论
为什么被折叠?



