Published:
Updated:


Solution

class ListNode {
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class RemoveDuplicatesFromSortedList {
    // The list is guaranteed to be sorted in ascending order.
    public static ListNode deleteDuplicates(ListNode head) {
        ListNode currentNode = head;
        // ν˜„μž¬ λ…Έλ“œμ™€ λ‹€μŒ λ…Έλ“œκ°€ null이 아닐 λ•Œ
        while (currentNode != null && currentNode.next != null) {
            if (currentNode.val == currentNode.next.val) { // 같을 경우
                currentNode.next = currentNode.next.next; // ν˜„μž¬ λ…Έλ“œκ°€ λ‹€λ‹€μŒ λ…Έλ“œλ₯Ό κ°€λ¦¬ν‚€κ²Œ 함
            } else { // 같지 μ•Šμ„ 경우
                currentNode = currentNode.next; // λ‹€μŒ λ…Έλ“œλ‘œ 이동
            }
        }
        return head; // pointer
    }
}

Leave a comment