给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
输入:head = [1,1,2] 输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3] 输出:[1,2,3]
算法逻辑
定义一个指针并且从头节点开始遍历链表。
如果当前节点的数据与下一个节点的数据相同,则将当前节点的next
指针指向下下个节点,从而跳过重复的节点。
如果当前节点的数据与下一个节点的数据不同,则继续遍历链表。
def check(self):
current = self.head
if self.head == None:
return
while current and current.next:
if current.data == current.next.data:
current.next = current.next.next
else:
current = current.next
完整代码
class Node:
def __init__(self,data):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = None
def insert(self,data):
new_node = Node(data)
if self.head == None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def check(self):
current = self.head
if self.head == None:
return
while current and current.next:
if current.data == current.next.data:
current.next = current.next.next
else:
current = current.next
def display(self):
if self.head == None:
return
else:
current = self.head
while current.next:
print(current.data,end = "->")
current = current.next
print(current.data,"\n")
list_0 = linked_list()
list_0.insert(1)
list_0.insert(1)
list_0.insert(2)
list_0.insert(2)
list_0.insert(3)
list_0.insert(3)
list_0.check()
list_0.display()
代码的时间复杂度为O(n),但此代码仅限于已排序的链表
在评论群评论留下自己的观点,博主下期会更新单链表的遍历,插入,输出,指定位置元素输出,指定元素的位置输出,返回链表长度以及链表的排序等操作,代码实现起来也不会很难,博主会以最通俗易懂的方式实现上述功能,不必担心看不懂,实际上你们会做的比我更好。