iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
生成式 AI

Chatting with ChatGPT——一天學習一題Leetcode系列 第 23

週三之LeetCode 83. Remove Duplicates from Sorted List

  • 分享至 

  • xImage
  •  

快結束了~~
事不宜遲,今天的題目大意是:
給你一個已經排序好的單向鏈結串列,請你刪除所有重複的元素,使每個數字只出現一次。
例如:
1 -> 1 -> 2 -> 3 -> 3
變成:
1 -> 2 -> 3

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        // 如果鏈結串列是空的(head == null),或只剩一個節點,就直接回傳 head
        if (head == null) return head;

        // 建立一個指標 current,用來從頭開始掃整個鏈結串列
        ListNode current = head;

        // 只要 current 的下一個節點還存在,就繼續檢查
        while (current.next != null) {

            // 如果目前節點的值 == 下一個節點的值,代表出現重複
            if (current.val == current.next.val) {
                // 把 current.next 往後跳一格,等於「跳過重複的節點」
                current.next = current.next.next;
            } else {
                // 否則就繼續往後走一格
                current = current.next;
            }
        }

        // 最後回傳處理好的鏈結串列頭
        return head;
    }
}

上一篇
D22- 704. Binary Search
系列文
Chatting with ChatGPT——一天學習一題Leetcode23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言