leetcode
[lang:python]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None
class Solution(object): #定义全局变量 def __init__(self): #标识三个相邻的节点 self._1 = None self._2 = None self._3 = None
#用于返回新链表的哨兵头节点 self.newListHead = ListNode(None) self.newListHead.next = None #用于生成新链表的当前节点 self.curListHead = self.newListHead #根据 self._2 的值,为新链表中增加一个节点 def genOneNodeToList(self): print self._2 newNode = ListNode(self._2) newNode.next = None self.curListHead.next = newNode self.curListHead = self.curListHead.next #检查当前节点 self._2 数据和前后节点是否相同 #如果分别不同与前后节点,则不重复 def duplicate(self, val): self._3 = self._2 self._2 = self._1 self._1 = val if self._2 != self._1 and self._2 != self._3: self.genOneNodeToList() def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ iterHead = head while True: if iterHead != None: self.duplicate(iterHead.val) else: self.duplicate(None) break iterHead = iterHead.next return self.newListHead.next
|
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏