[코테 풀이] Remove Duplicates from Sorted List

시내·2024년 6월 5일

Q_83) Remove Duplicates from Sorted List

출처 : https://leetcode.com/problems/remove-duplicates-from-sorted-list/

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.

/**
 * 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) {
        ArrayList arrayList = new ArrayList();
        while (head != null) {
            if (!arrayList.contains(head.val)) {
                arrayList.add(head.val);
            }
            head = head.next;
        }
        if (arrayList.size() >= 1) {
            ListNode l = new ListNode((int) arrayList.get(0));
            ListNode n = l;
            for (int a = 1; a < arrayList.size(); a++) {
                n.next = new ListNode((int) arrayList.get(a));
                n = n.next;
            }
            return l;
        }
        return null;
    }
}

💫 ListNode 연결방법 유의하기

profile
contact 📨 ksw08215@gmail.com

0개의 댓글