劍指offer:刪除連結串列中重複的結點
阿新 • • 發佈:2018-12-11
題目描述
在一個排序的連結串列中,存在重複的結點,請刪除該連結串列中重複的結點,重複的結點不保留,返回連結串列頭指標。 例如,連結串列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 pHead==None or pHead.next==None: return pHead if pHead.val==pHead.next.val: node=pHead.next while node!=None and node.val==pHead.val: node=node.next return self.deleteDuplication(node) else: pHead.next=self.deleteDuplication(pHead.next) return pHead
用遞迴來做,如果下一個節點和現在沒有重複,就遞迴到下一個節點,如果重複了,用一個node儲存pHead.next,繼續next到不重複了,遞迴到node結點,這樣就把重複結點都跳過了。