문제 이해
- 링크드 리스트에서 특정 값을 삭제하라
해결 전략
- 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로 연결할 수 있다.
'PS' 카테고리의 다른 글
Leetcode 21. Merge Two Sorted Lists (0) | 2022.04.26 |
---|---|
Leetcode 234. Palindrome Linked List (1) | 2022.04.26 |
Leetcode 876. Middle of the Linked List (0) | 2022.04.25 |
Leetcode 2207. Maximize Number of Subsequences in a String (1) | 2022.04.25 |
Leetcode 2233. Maximum Product After K Increments (0) | 2022.04.24 |