# 在一个排序链表中,删除重复的点
# 利用python实现链表的
class Node:
def __init__(self, data, next):
self.data = data
self.next = next
# 包含头结点的链表
class LinkList:
def __init__(self, input):
self.headNode = Node(None, None)
if input is None:
pass
else:
work = self.headNode
for i in input:
newnode = Node(i, None)
work.next = newnode
work = work.next
def travelLinkList(self):
work = self.headNode
while work.next is not None:
print(work.next.data)
work = work.next
#
def delete_duplicate_node(head_node):
# 定义3个指针,分别是pre_p, cur_p, next_p
# 指针初始化
if head_node is None:
return
else:
pre_p = head_node
if pre_p.next is not None:
cur_p = pre_p.next
else:
return
if cur_p.next is not None:
next_p = cur_p.next
else:
return
# 开始删除
while next_p is not None:
if cur_p.data != next_p.data: # 如果cur_p和next_p指向的值不想等,那么三个指针整体向后移动一位
pre_p = cur_p
cur_p = next_p
next_p = next_p.next
else: # 发现重复的值,则将cur_p指针向后移动到不重复的节点
while cur_p and cur_p.data == next_p.data:
cur_p = cur_p.next
# pre_p 与 cur_p 连接
pre_p.next = cur_p
if cur_p is None: # 如果cur_p为None,说明pre_p之后的所有节点都为None
next_p = None # next_p置为None,跳出while
else:
next_p = cur_p.next # 如果cur_p非None,next_p指向cur_p的下一个节点,继续while
return head_node
if __name__ == '__main__':
# 测试用例
# array = [1, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6, 6]
# array = [6, 6, 6, 6, 1]
array = [1,2,3,4,5,7]
link_list = LinkList(array)
head_node = delete_duplicate_node(link_list.headNode)
link_list.travelLinkList()