PS

Leetcode 203. Remove Linked List Elements

Bryan Lee 2022. 4. 26. 12:17

문제 이해

- 링크드 리스트에서 특정 값을 삭제하라 

 

해결 전략

- dummy라는 임의의 노드를 생성합니다.

- dummy.next에 head를 대입합니다. 

- curr에 dummy를 대입합니다. 

- curr를 순회하면서 val에 해당되는 값을 제거합니다.  

 

구현

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode curr = dummy;
        
        while(curr.next != null){
            if(curr.next.val == val){
                curr.next = curr.next.next;
            }else{
                curr = curr.next;
            }
        }
        
        return dummy.next;
        
    }
}

 

피드백

- 첫번째 원소부터 시작하기 위해, dummy라는 임의의 노드를 만들어서,

  dummy.next = head로 연결할 수 있다.