题目描述:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5.
Solutions
这里需要注意的是要把重复的结点一个不剩的删掉,而不是剩下成独一的结点,用两重循环是可以解决的。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
first = ListNode(-1)
first.next = pHead
pre = first
cur = pHead
while cur and cur.next:
if cur.val != cur.next.val:
pre = cur
cur = cur.next
else:
val = cur.val
while cur and val == cur.val:
cur = cur.next
pre.next = cur
return first.next
# 运行时间:29ms
# 占用内存:5712k