[关闭]
@Scrazy 2017-04-12T13:58:17.000000Z 字数 588 阅读 969

删除链表中的重复元素

python 算法


所谓的删除是指:
如果这个值重复了,就把它删除的一个不剩。

思路:
1. 假设 链表顺序是 A->B->C->D->E-> ...
2. 构建一个新的链表 current
3. if 分支用于删除多个连续重复节点 例如 A B C D ...
4. else 使用 current 作为中间变量,删除非连续的重复值 eg: B D ...

  1. # -*- coding:utf-8 -*-
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def deleteDuplication(self, pHead):
  8. if not pHead:
  9. return None
  10. elif not pHead.next:
  11. return pHead
  12. current = None
  13. if pHead.next.val == pHead.val: # 此分支用于删除多个连续重复的节点
  14. current = pHead.next.next
  15. while current and current.val == pHead.val:
  16. current = current.next
  17. return self.deleteDuplication(current)
  18. else:
  19. current = pHead.next
  20. pHead.next = self.deleteDuplication(current)
  21. return pHead
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注