题目

Remove all elements from a linked list of integers that have value val.

Example:

  1. Input: 1->2->6->3->4->5->6, val = 6
  2. Output: 1->2->3->4->5

题意

将给定链表中所有含有指定值的结点删除。

思路

注意需要连续删除结点的情况。


代码实现

Java

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode removeElements(ListNode head, int val) {
  11. ListNode dumb = new ListNode(0);
  12. dumb.next = head;
  13. ListNode pre = dumb;
  14. ListNode cur = head;
  15. while (cur != null) {
  16. if (cur.val == val) {
  17. pre.next = cur.next;
  18. cur = cur.next;
  19. } else {
  20. pre = pre.next;
  21. cur = cur.next;
  22. }
  23. }
  24. return dumb.next;
  25. }
  26. }

JavaScript

  1. /**
  2. * @param {ListNode} head
  3. * @param {number} val
  4. * @return {ListNode}
  5. */
  6. var removeElements = function (head, val) {
  7. let dummy = new ListNode(0, head)
  8. let pre = dummy
  9. let cur = head
  10. while (cur) {
  11. if (cur.val === val) {
  12. pre.next = cur.next
  13. } else {
  14. pre = cur
  15. }
  16. cur = cur.next
  17. }
  18. return dummy.next
  19. }