题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
- 定义两个结点,一前一后
- 如果后一个结点和它的下一个结点不相等,前一个结点和后一个结点分别向后移
- 如果相同,就先记录这个结点值,后一个结点继续向后遍历,直到不等
- 把前一个结点的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 None
head=ListNode(-1)
head.next=pHead
first=head
while pHead and pHead.next:
if pHead.val==pHead.next.val:
val=pHead.val
while pHead and pHead.val==val:
pHead=pHead.next
first.next=pHead
else:
first=pHead
pHead=pHead.next
return head.next
测试用例
if __name__=='__main__':
s=Solution()
head=ListNode(1)
phead=head
data=[2,3,3,4,4,5]
for i in data:
node=ListNode(i)
phead.next=node
phead=phead.next
head=s.deleteDuplication(head)
while head:
print(head.val),
head=head.next