题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
题目地址
思路
要删除有序链表中所有的重复节点,而头结点有可能就是重复节点。这样的比较好的解决方式就是新建头结点,然后往后遍历,同样的值就全部略过。
Python
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(3) node5 = ListNode(4) node6 = ListNode(4) node7 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 class Solution: def deleteDuplication(self, pHead): # write code here if not pHead or not pHead.next: return pHead first = ListNode(-1) first.next = pHead last = first cur = pHead while cur and cur.next: if cur.val != cur.next.val: cur = cur.next last = last.next else: val = cur.val while cur and cur.val == val: cur = cur.next last.next = cur return first.next if __name__ == '__main__': result = Solution().deleteDuplication(node1) while result: print(result.val, end = ' ') result = result.next
作者:huangqiancun
出处:http://www.cnblogs.com/huangqiancun/
本博客若无特殊说明则由作者原创发布,欢迎转载,但请注明出处 :)