需求
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
代码
# 定义链表节点类
class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = next# todo 创建删除重复节点的方法
def deleteDuplicates(head):# 如果链表不存在或者链表为空if not head or not head.next:return head# 创建一个指针指向头节点current = headwhile current and current.next:# 如果当前节点与下一个节点值相等,则跳过重复的节点if current.val == current.next.val:current.next = current.next.nextelse:current = current.nextreturn head# todo 创建将列表转换为链表的方法
def createLinkedList(arr):# 创建dummy指针指向头节点dummy = ListNode(0)# 创建尾指针tail = dummyfor num in arr:tail.next = ListNode(num)tail = tail.nextreturn dummy.next# 创建示例1的链表
arr1 = [1, 1, 2]
head1 = createLinkedList(arr1)# 删除重复元素并输出结果
result1 = deleteDuplicates(head1)
while result1:print(result1.val, end=" -> ")result1 = result1.next
print("None")# 创建示例2的链表
arr2 = [1, 1, 2, 3, 3]
head2 = createLinkedList(arr2)# 删除重复元素并输出结果
result2 = deleteDuplicates(head2)
while result2:print(result2.val, end=" -> ")result2 = result2.next
print("None")