203. Remove Linked List Elements
题目
原始地址:https://leetcode.com/problems/remove-linked-list-elements/#/description
/**
* 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) {
}
}
描述
删除链表中所有值与给定值相同的节点。
分析
最简单的题目了,不多解释,循环递归都能做。注意循环解法可以使用一个小技巧,head之前再插入一个节点,这样头节点的就不需要做特殊处理了。
解法1
/**
* 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 node = new ListNode(0), curr = node;
node.next = head;
while (curr.next != null) {
if (curr.next.val == val) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return node.next;
}
}
解法2
/**
* 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 null;
}
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}