题目
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
遍历链表,跳过所有重复结点。
代码
# -*- 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 or not pHead.next:
return pHead
node = pHead
next = pHead.next
pre = ListNode(0)
pre.next = node
res_pre = pre
while node and next:
if node.val == next.val:
while next and node.val == next.val:
next = next.next
pre.next = next
node = next
if node:
next = node.next
else:
pre = node
node = node.next
next = next.next
return res_pre.next