题目分析:
这一题是给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。如:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
解题思路:(描述的稀里糊涂,希望你能看懂)
这个题我们先逐位循环,如果下一位的值等于下下一位的值,就标记下下一位的位置。如果下一位的值不等于下下一位的值,就令指针后移,如果下一位的值等于下下一位的值令该位置的下一位为标记位置的下一位(下下下一位)。
测试代码:(非提交代码,提交代码在下面)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def print_listNode(listNode: ListNode):
if not listNode:
print(None)
return
bf_listNode = listNode
while bf_listNode.next:
print(bf_listNode.val, end='-->')
bf_listNode = bf_listNode.next
print(bf_listNode.val)
def creat_listNode(nums: list):
if not nums: return None
bf_head = head = ListNode(nums[0])
for i in range(1, len(nums)):
head.next = ListNode(nums[i])
head = head.next
head.next = None
return bf_head
class Solution:
def deleteDuplicates(self, head):
if head == None or head.next == None:
return head
dummy = ListNode(0); dummy.next = head
p = dummy
tmp = dummy.next
while p.next:
while tmp.next and tmp.next.val == p.next.val:
tmp = tmp.next
if tmp == p.next:
p = p.next
tmp = p.next
else:
p.next = tmp.next
return dummy.next
print_listNode(Solution().deleteDuplicates(creat_listNode([1,2,3,3,4,4,5])))
print_listNode(Solution().deleteDuplicates(creat_listNode([1,2,3,3,3,4,4,5])))
print_listNode(Solution().deleteDuplicates(creat_listNode([1,1,1,2,3])))
print_listNode(Solution().deleteDuplicates(creat_listNode([1])))
print_listNode(Solution().deleteDuplicates(creat_listNode([])))
print_listNode(Solution().deleteDuplicates(creat_listNode([1,2,2])))
print_listNode(Solution().deleteDuplicates(creat_listNode([1,1])))
提交代码:(Runtime: 48 ms, faster than 79.40 %)
class Solution:
def deleteDuplicates(self, head):
if head == None or head.next == None:
return head
dummy = ListNode(0); dummy.next = head
p = dummy
tmp = dummy.next
while p.next:
while tmp.next and tmp.next.val == p.next.val:
tmp = tmp.next
if tmp == p.next:
p = p.next
tmp = p.next
else:
p.next = tmp.next
return dummy.next