题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
方法一
在遍历的时候,记录上一个不重复的节点pPre,当前节点pThis,下个节点pNext。
在遍历pThis的时候如果当前节点pThis的值跟后面的几个节点数值相同,需要找到下个不同的节点,删除重复节点,更新pPre和pThis;
如果前节点pThis的值跟后面的节点数值不同,直接更新pPre和pThis。
如果pHead就是重复的,需要更新pHead。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
# write code here
if pHead == None or pHead.next == None:
return pHead
pPre = None
pThis = pHead
pNext = None
while(pThis):
# 当前节点和当前节点的next值相等,则循环
if(pThis.next and pThis.next.val == pThis.val):
pNext = pThis.next # PNext指向当前节点的下一个节点
#判断是否下下一个节点仍然与当前节点的值相等
while(pNext.next and pNext.next.val == pThis.val):
pNext = pNext.next #重复元素序列中的后一个
if(pThis == pHead):
pHead = pNext.next
else:
pPre.next = pNext.next
pThis = pNext.next #跳过重复元素
else:
# 不相等,则指向下个节点
pPre = pThis
pThis = pThis.next
return pHead
方法二
构建一个新的链表,存储不重复的节点。
class Solution:
def deleteDuplication(self, pHead):
# write code here
if not pHead:
return None
a_list = []
while pHead:
a_list.append(pHead.val)
pHead = pHead.next
new_list = [i for i in a_list if a_list.count(i)==1]
if new_list:
root = pHead = ListNode(new_list[0])
for i in range(1,len(new_list)):
pHead.next = ListNode(new_list[i])
pHead = pHead.next
return root
else:
return None
方法三
链接:https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef?answerType=1&f=discussion
来源:牛客网
def deleteDuplication(self, pHead):
# write code here
if not pHead:
return pHead
#为了防止头结点是重复的,定义一个新结点指向头结点
temp = ListNode(0)
temp.next = pHead
pre, nex = temp, pHead
while nex:
if nex.next and nex.next.val == nex.val:
#如果出现了和当前节点相同的值的时候,当前节点前移一位
while nex.next and nex.next.val == nex.val:
nex = nex.next
pre.next = nex.next#只是指向,并没有动pre,相当于删除
nex = nex.next
else:
pre = pre.next
nex = nex.next
return temp.next