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的节点
- 非递归
维持head的上一个节点prev(为方便用到了头节点),跳过等于val的节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode fakeHead = new ListNode(-1);
fakeHead.next = head;
ListNode prev = fakeHead;
while (head != null) {
if (head.val == val) prev.next = head.next;
else prev = prev.next;
head = head.next;
}
return fakeHead.next;
}
}
- 递归
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}