leecode-83. 删除排序链表中的重复元素

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

1
2
3
4
5
6
7
8
示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:sarizzm time:2021/1/6 0006
# 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):
if head is None:
return head
pre = head
while pre.next:
next_node = pre.next
if pre.val == next_node.val:
pre.next = next_node.next
else:
pre = next_node
return head


def generateNode(nx):
node = ListNode()
p1 = node

for i in nx:
p1.next = ListNode(i)
p1 = p1.next
return node.next


n1 = [1, 3, 3, 5, 7, 7, 10]
n2 = [1, 1, 2]
n3 = [1, 2, 3, 3]
n5 = [1]
n4 = []
node1 = generateNode(n1)
node2 = generateNode(n2)
node3 = Solution().deleteDuplicates(generateNode(n4))
while (node3):
print(node3.val)
node3 = node3.next

执行用时:44 ms, 在所有 Python3 提交中击败了82.26%的用户

内存消耗:14.8 MB, 在所有 Python3 提交中击败了16.02%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}

//作者:LeetCode
//链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/solution/shan-chu-pai-xu-lian-biao-zhong-de-zhong-fu-yuan-s/