Question

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

二刷:

  • Method 1: 创建一个新的结点,如果符合要求则向这个结点后添加。 ```Java /**
  • 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 dummy = new ListNode(0); ListNode dummyCur = dummy; ListNode cur = head; while(cur != null){ if(cur.val != val){ dummyCur.next = cur; dummyCur = dummyCur.next; } cur = cur.next; } dummyCur.next = null; return dummy.next; } } ```

  • Method 2: 原地去除结点,所以要记录前结点。 ```Java /**
  • 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 dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode cur = head; while(cur != null){ while(cur != null && cur.val == val){ cur = cur.next; } pre.next = cur; if(cur == null) return dummy.next; pre = pre.next; cur = cur.next; } return dummy.next; } } ```