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
/**
* 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) {
if(head==null) return head;
head.next = removeElements(head.next, val);
return head.val==val ? head.next : head;
}
}也可以迭代的方式,先构建一个头部节点
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode fakeHead = new ListNode(-1);
fakeHead.next = head;
ListNode curr = head, prev = fakeHead;
while (curr != null) {
if (curr.val == val) {
prev.next = curr.next;
} else {
prev = prev.next;
}
curr = curr.next;
}
return fakeHead.next;
}
}
本文介绍了一种从链表中移除特定值的所有元素的方法,提供了递归及迭代两种实现方式,并详细展示了每种方法的具体步骤。
734

被折叠的 条评论
为什么被折叠?



