83. 删除排序链表中的重复元素
为保证权益,题目请参考 83. 删除排序链表中的重复元素(From LeetCode).
解决方案1
CPP
C++
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == nullptr)
{
return nullptr;
}
ListNode *preNode = nullptr;
ListNode *curNode = head;
while (curNode != nullptr && curNode->next != nullptr)
{
preNode = curNode;
curNode = curNode->next;
if (curNode == nullptr)
{
break;
}
if (curNode->val == preNode->val)
{
ListNode *tmpNode = curNode;
preNode->next = curNode->next;
delete tmpNode;
curNode = preNode;
}
}
return head;
}
};
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
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
Python
python
# LeetCode 83
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None:
return head
curNode = head
preNode = None
while curNode is not None and curNode.next is not None:
preNode = curNode
curNode = curNode.next
if curNode is None:
break
if curNode.val == preNode.val:
tmpNode = curNode
preNode.next = curNode.next
del tmpNode
curNode = preNode
return head
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
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