leetcode-83-链表题-删除排序链表中的重复元素

题目

1.png

解法

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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 || !head->next) return head;

ListNode *a = head;
ListNode *b = head->next;
while(b){
if(a->val == b->val){
if(!b->next)
a->next = b->next;
b = b->next;
}else{
a->next = b;
a = a->next;
b = b->next;
}
}

return head;
}
};

// 直接法
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;

ListNode *ptr{head};
while(ptr->next){
if(ptr->val == ptr->next->val){
ptr->next = ptr->next->next;
}else{
ptr = ptr->next;
}
}

return head;
}
};