LeetCode 83.Remove Duplicates from Sorted List(從已排序連結串列中除去重複) Easy/Linked List

押切徹發表於2020-11-14


1.Description

Given a sorted linked list, delete all duplicates such that each element appear only once.


2.Example

Input: 1->1->2
Output: 1->2

3.Solution

感覺這裡比較繞的是while迴圈的條件,current != null是為了除去head是空的情況,current.next != null是為了保證current.next.next能取到值,至少可以取到一個null。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode current = head;
        while (current != null && current.next != null) {
            if (current.next.val == current.val) {
                current.next = current.next.next;
            } else {
            current = current.next;
            }
        }
        return head;
    }
}

相關文章