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;  
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ