首页 > 代码库 > 203. 移除链表中的元素 Remove Linked List Elements

203. 移除链表中的元素 Remove Linked List Elements

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

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

题意:移除链表中指定val的元素

注意:考虑删除节点在尾部,以及连续删除两个相邻节点的情况

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * public int val;
  5. * public ListNode next;
  6. * public ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public void Delete(ListNode node) {
  11. node.val = node.next.val;
  12. node.next = node.next.next;
  13. }
  14. public ListNode RemoveElements(ListNode head, int val) {
  15. ListNode node = head;
  16. ListNode last = null;
  17. while (node != null) {
  18. if (node.val == val) {
  19. if (node.next != null) {
  20. Delete(node);
  21. continue;
  22. } else {
  23. if (last != null) {
  24. last.next = null;
  25. } else {
  26. return null;
  27. }
  28. }
  29. }
  30. last = node;
  31. node = node.next;
  32. }
  33. return head;
  34. }
  35. }




null


203. 移除链表中的元素 Remove Linked List Elements