微頭條丨#yyds干貨盤(pán)點(diǎn)# LeetCode程序員面試金典:移除重復(fù)節(jié)點(diǎn)

2022-12-06 19:16:21 來(lái)源:51CTO博客


(資料圖片)

題目:

編寫(xiě)代碼,移除未排序鏈表中的重復(fù)節(jié)點(diǎn)。保留最開(kāi)始出現(xiàn)的節(jié)點(diǎn)。

示例1:

輸入:[1, 2, 3, 3, 2, 1]

輸出:[1, 2, 3]

示例2:

輸入:[1, 1, 1, 1, 2]

輸出:[1, 2]

代碼實(shí)現(xiàn):

class Solution {    public ListNode removeDuplicateNodes(ListNode head) {        if (head == null) {            return head;        }        Set occurred = new HashSet();        occurred.add(head.val);        ListNode pos = head;        // 枚舉前驅(qū)節(jié)點(diǎn)        while (pos.next != null) {            // 當(dāng)前待刪除節(jié)點(diǎn)            ListNode cur = pos.next;            if (occurred.add(cur.val)) {                pos = pos.next;            } else {                pos.next = pos.next.next;            }        }        pos.next = null;        return head;    }}

標(biāo)簽: 刪除節(jié)點(diǎn)

上一篇:世界觀點(diǎn):?jiǎn)栴}解決系列:ftp并發(fā)讀取文件內(nèi)容時(shí),會(huì)出現(xiàn)ftp連接數(shù)過(guò)多,進(jìn)而導(dǎo)致讀取文件出現(xiàn)問(wèn)題
下一篇:天天微頭條丨#yyds干貨盤(pán)點(diǎn)# 名企真題專題:最大乘積