Leetcode [Easy] 203 - Remove Linked List Elements
LeetCode 203
Remove Linked List Elements
문제
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
나의 코드
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
let prev = null;
let cur = head;
while (cur) {
if (head.val === val) {
// 시작점을 찾기 위해 head 바꿔줌
head = head.next;
} else if (cur.val === val) {
// val 발견
prev.next = cur.next;
} else if (cur.val !== val) {
// val 아닐 때
prev = cur;
}
cur = cur.next;
}
return head;
};
참고 코드
배운점
Subscribe via RSS