資料結構 java語言實現刪除鍊錶中重複結點

2021-09-23 07:47:46 字數 625 閱讀 3357

目錄

1 題目描述

2 解題思路

3 **實現

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

首先,定義乙個虛擬結點node,其後儲存單鏈表中不重複的結點,最後返回node.next即可。

那麼問題來了,如何找到不重複的結點呢?而且重複的結點不一定是2個相鄰,有可能3個或者多個相鄰,因為是排序的鍊錶,我們就可以用while迴圈一直遍歷,直到找到重複結點的下一結點為止。

因此,我們需要知道迴圈條件的出口:定義乙個結點cur,從頭開始遍歷鍊錶,當cur為null時,遍歷完成。在遍歷的過程中,比較cur與cur.next的值是否相等(在cur.next != null的情況下):

public node delallnode()

cur = cur.next;

//將temhead.next的指向更新,但保持temhead的值不變

temhead.next = cur;

}else

}return node.next;

}

資料結構 移除鍊錶元素(基於java語言實現)

刪除鍊錶中等於給定值 val 的所有節點。示例 輸入 1 2 6 3 4 5 6,val 6輸出 1 2 3 4 5方法1 思想 遍歷原鍊錶的所有節點,比較每個節點的 val 值,將與 val 值不相等的節點挨個插入乙個新的鍊錶,每遇到乙個與 val 值 不相等的節點,就將該節點插入新鍊錶,且需要尾...

資料結構C語言實現 從鍊錶中刪除結點

如下 include includetypedef struct node node linklist 建立鍊錶 linklist creat linklist int n else tail node new node return head node 從鍊錶中刪除結點 void delelink...

資料結構C語言實現 線性鍊錶

declaration.h ifndef declaration h included define declaration h included define true 1 define false 0 define ok 1 define error 0 define infeasible 1 ...