题目
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解答
解法一:非递归
具体流程:
- 声明一个虚拟头节点,去除极端条件干扰。例如:head 的值是 val 的情况。
- 遍历链表,如果当前结点的值等于 val ,就让前驱指向当前结点的下一个。(相当于删除了当前结点。)
- 否则继续遍历。
代码
/**
* 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;
while(pre.next != null) {
ListNode cur = pre.next;
if(cur.val == val) {
pre.next = cur.next;
cur.next = null;
} else {
pre = pre.next;
}
}
return dummy.next;
}
}
结果

解法二:递归
就三行代码,没什么好说的。。
代码
/**
* 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) {
if(head == null) return null;
head.next = removeElements(head.next, val);
return head.val != val ? head : head.next;
}
}
结果

556



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



