一、题目

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

Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

删除链表中等于给定值val的所有节点。

二、解题思路

删除链表中指定值,找到其前一个节点即可,将 next 指向下一个节点即可

三、解题代码

  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. public class Solution {
  10. /**
  11. * @param head a ListNode
  12. * @param val an integer
  13. * @return a ListNode
  14. */
  15. public ListNode removeElements(ListNode head, int val) {
  16. ListNode dummy = new ListNode(0);
  17. dummy.next = head;
  18. ListNode curr = dummy;
  19. while (curr.next != null) {
  20. if (curr.next.val == val) {
  21. curr.next = curr.next.next;
  22. } else {
  23. curr = curr.next;
  24. }
  25. }
  26. return dummy.next;
  27. }
  28. }