劍指offer 刪除鍊錶中重複的結點

2021-08-28 08:28:54 字數 778 閱讀 9473

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。 例如,鍊錶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結點,這樣就把重複結點都跳過了。

劍指offer 鍊錶 刪除鍊錶中的重複節點

題目在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 思路分析 思路一 使用linkedlist儲存不重複節點,重構鍊錶 分析評價 這個方法是乙個比較直接且容易想到的方法,使用時只要注意一些情況...

劍指offer 刪除鍊錶中重複的結點(鍊錶)

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 class solution listnode ans newlistnode 1 ans next phead listnode link a...

劍指Offer 鍊錶 刪除鍊錶中重複的結點

題目 在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5。注意該鍊錶為排序鍊錶,重複的節點不保留哦!public class listnode 1 遞迴 遞迴的方法就像是先判斷第乙個節點和之後的節...