leetcode-83-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.

分析


常规题目,画个草图比较容易理解

解决方案1(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
/**
* 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) {
ListNode* pivot = head;
if(pivot && pivot->next){
while(pivot->next){
while(pivot->val == pivot->next->val){
pivot->next = pivot->next->next;
if(pivot->next == NULL) break;
}
pivot = pivot->next;
if(pivot == NULL){
return head;
}
}
}
return head;
}
};

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil {
return nil
}
current := head
for current.Next != nil {
if current.Val == current.Next.Val {
current.Next = current.Next.Next
} else {
current = current.Next
}
}
return head
}

相关问题


题目来源