删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
分析:
题解一:
常规思路,创建两个 ListNode 类型的节点,一个作为头节点记录,另一个作为其后续节点,遍历 head 链表,当 head 节点的值不等于 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) {
if(head == null)
return null;
ListNode newNode = new ListNode(0);
ListNode newHead = newNode;
while(head != null) {
if(head.val != val) {
ListNode t = new ListNode(head.val);
newNode.next = t;
newNode = newNode.next;
}
head = head.next;
}
return newHead.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.next : head;
}
}