💻 Coding Problems Solving/Two Pointers | Binary Search| LinkedList

[LeetCode] Remove Duplicates from Sorted List II

Kim_dev 2023. 7. 12. 21:40

1. 문제 : https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/

 

2. 풀이

현재값과 다음 값이 같으면 커서 계속 이동해주고

다음 값과 다를때 이전값의 next와 지금이 같은지 확인해주고

같다면 다음값 & 현재값 다음으로 넘기고, 다르면 다음값의 next를 현재값의 next로 맞춰준다.

 

3. 코드

/**
 * 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; }
 * }
 */
import java.util.*;

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dHead = new ListNode(-1);
        dHead.next = head;
        ListNode prev = dHead;
        ListNode cur = head;
        while(cur != null){
            while(cur.next!=null && cur.val==cur.next.val){
                cur=cur.next;
            }
            if(prev.next == cur){
                prev=prev.next;
            } else{
                prev.next=cur.next;
            }
            cur = cur.next;
        }
        return dHead.next;  
    }
}