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

2022-03-29 11:37:36 字數 883 閱讀 5719

56. 刪除有序鍊錶中的重複結點

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。 例如,鍊錶1->2->3->3->4->4->5 處理後為 1->2->5

借助輔助頭結點,可避免單獨討論頭結點的情況。設定兩個結點 pre 和 cur,當 cur 和 cur.next 值相等,cur 一直向前走,直到不等退出迴圈,這時候 cur 指的值還是重複值,調整 cur 和 pre 的指標再次判斷

/*

public class listnode

}*/

1

public

class

solution 78

//每訪問乙個結點,迴圈判斷是否重複

9 listnode cur = phead; //

指向當前結點

10//

建立乙個輔助頭結點,指向前乙個元素的指標,方便刪除

11 listnode head = new

listnode(integer.min_value);

12 head.next =phead;

13 listnode pre =head;

1415

while(cur != null

)21 cur = cur.next; //

這個cur所指結點即是下乙個不重複的結點

22 pre.next =cur;

23 }else27}

28return

head.next;29}

30 }

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

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 注意是把重複的刪除,不是刪掉重複的 coding utf 8 class listnode def init self,x self.val x...

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

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 思路1 用乙個set來記錄重複的結點 class solution listnode new phead newlistnode 1 這個操作主...

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

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 注意如果是頭結點的判斷 另外,每次 next的時候都需要判斷當前節點是否為空 struct listnode class solution 如果...