코딩테스트/알고리즘 문제풀이

[JAVA] 83. Remove Duplicates from Sorted List

지과쌤 2022. 9. 14.
반응형

목차

문제

    Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

     

    Example 1:

    Input: head = [1,1,2]
    Output: [1,2]
    

    Example 2:

    Input: head = [1,1,2,3,3]
    Output: [1,2,3]
    

     

    Constraints:

    • The number of nodes in the list is in the range [0, 300].
    • -100 <= Node.val <= 100
    • The list is guaranteed to be sorted in ascending order.

    풀이

    JAVA 

    재귀함수 사용

    /**
     * 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; }
     * }
     */
    
    public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null) {
            	return head;
            }
            
            head.next = deleteDuplicates(head.next);
            
            return head.val == head.next.val ? head.next : head;
    }

    재귀 사용하지 않은 풀이 (완벽한 풀이 아니므로 참고만.)

    /**
     * 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; }
     * }
     */
    
    private ListNode deleteDuplicates(ListNode head) {
            ListNode current = head;
            
            while (current != null && current.next != null) {
                if (current.val == current.next.val) {
                    current.next = current.next.next;
                } 
                else {
                    current = current.next;
                }
            }
            
            return head;
    }
    반응형

    '코딩테스트 > 알고리즘 문제풀이' 카테고리의 다른 글

    [JAVA] 70. Climbing Stairs  (0) 2022.09.19
    [JAVA] 69. Sqrt(x)  (0) 2022.09.16
    이후 문제 풀이 => LeetCode  (0) 2022.09.09
    [파이썬] 2750 : 수 정렬하기  (0) 2021.08.31
    [파이썬] 1436 : 영화감독 숌  (0) 2021.08.30

    댓글

    💲 추천 글