Remove all elements from a linked list of integers that have value val.javascript
Example:java
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
將給定鏈表中全部含有指定值的結點刪除。code
注意須要連續刪除結點的狀況。ip
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dumb = new ListNode(0); dumb.next = head; ListNode pre = dumb; ListNode cur = head; while (cur != null) { if (cur.val == val) { pre.next = cur.next; cur = cur.next; } else { pre = pre.next; cur = cur.next; } } return dumb.next; } }
/** * @param {ListNode} head * @param {number} val * @return {ListNode} */ var removeElements = function (head, val) { let dummy = new ListNode(0, head) let pre = dummy let cur = head while (cur) { if (cur.val === val) { pre.next = cur.next } else { pre = cur } cur = cur.next } return dummy.next }