leetcode解题: Remove Duplicates from Sorted List (83)

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.

Hide Tags

解法1:Two pointers O(N)

用双指针,比较两node的值,如果相等,则前面的指针跳过下一个node(删除后一个node)。如果不相等,则两个指针同时向后移动直到尾部。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* res = head;
ListNode* ptr = head->next;
while (ptr != NULL) {
if (head->val == ptr->val) {
ListNode* temp = ptr;
head->next = ptr->next;
delete temp;
ptr = head->next;
} else {
head = head->next;
ptr = ptr->next;
}
}
return res;
}
};

Java

1