Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
给定一个排序链表,删除所有重复的元素每个元素只留下一个。
Examples
Input: 1->1->2
Output: 1->2
Input: 1->1->2->3->3
Output: 1->2->3
Answer
Use two pointers. One always point to the first node of the same value and another one is to find the next node with the different value of the first node.
Time Complexity
O(n)
Code
C++
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;
ListNode* temp = head;
while(temp->next)
{
if(temp->val == temp->next->val)
temp->next = temp->next->next;
else
temp = temp->next;
}
return head;
}
};