版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014568072/article/details/87910685
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
《剑指offer》P273
- 方法一
考虑借助一个辅助list
,每次放入一个node
,记录当前结点的值currValue
。当下一个结点值与currValue
相等,则将结点pop()
出栈,移动指针直到找到一个值不同的结点。当下一个结点与currValue
值不等,则将该结点append
进去,然后更新currValue
值,并后移。 - 方法二
书中介绍的方法,新建一个head
作为头指针,设置两个指针p1
和p2
一前一后,比较两个结点的值,分为两种情况:- 如果相等,则移动
p2
找到第一个不相等的结点,令p1
指向该结点,p2
依旧指向p1.next
。 - 如果不相等,则直接将
p1
结点连接到新的链表后,将p1
和p2
分别后移。
- 如果相等,则移动
code
- 方法一
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
if not pHead:
return pHead
node_stack = []
curVal = pHead.val
node_stack.append(pHead)
node = pHead.next
while node:
if node.val == curVal:
n = node_stack.pop()
while node.val == curVal:
node = node.next
if not node:
break
else:
node_stack.append(node)
curVal = node.val
node = node.next
phead = ListNode(-1)
head = phead
while node_stack:
node = node_stack.pop(0)
head.next = node
head = head.next
head.next = None
return phead.next
- 方法二
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
if not pHead:
return pHead
p0 = ListNode(-1)
head = p0
p1 = pHead
p2 = pHead.next
while p2:
# 如果p1与p2值相等,则向后移动p2直到找到不相等的值
if p1.val == p2.val:
# 找到该重复结点后的第一个结点
while p2 and p1.val == p2.val:
p2 = p2.next
p1 = p2
if p1:
p2 = p1.next
else:
break
# 如果p1与p2值不相等
else:
p0.next = p1
p0 = p0.next
p1 = p1.next
p2 = p2.next
p0.next = p1
return head.next