Algorithm/LeetCode

LeetCode 83. Remove Duplicates from Sorted List

hhsaebom 2021. 1. 12. 15:38

문제 링크: leetcode.com/problems/remove-duplicates-from-sorted-list/

 

Remove Duplicates from Sorted List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 요약: 정렬된 순서로 링크드리스트가 주어질때, 중복된 원소를 뺀 링크드리스트를 반환 하시오.

 

문제 접근: 정렬되있기 때문에, 바로 직전값이랑만 비교하면 된다. 생각은 쉽지만 코드를 처음 작성할때는 잘 안됬었다.

 

/**
 * 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) {
        if (head == null) return head;
        ListNode originNode = head;
        // 이전값을 비교하기 위해 선언
        ListNode previousNode = null;
        
        while (head != null) {
            int currentVal = head.val;
            // 처음일때 거르기 위해 작성
            if (previousNode != null) {
                int previousVal = previousNode.val;
                // 현재 노드값이 이전노드값이랑 같으면 이전 노드의 다음 노드를 현재노드의 다음 노드에 연결
                if (currentVal == previousVal) {
                    previousNode.next = head.next;
                    // 다르다면 이전 노드는 현재 노드로 변경
                } else {
                    previousNode = head;
                }
            } else {
                previousNode = head;
            }
            // 모든 비교가 끝나면 다음 노드로 건너뜀.
            head = head.next;
        }

        return originNode;
    }
}

주의할 점은 반환할때 가장 처음 노드를 반환해야한다.