题目
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
我的解法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head==null) return head;
ListNode q=head;
ListNode p=new ListNode(0);
p.next=head;
ListNode res=p;
while(q.val!=val||q==null){
q=q.next;
p=p.next;
}
if(q!=null){
p.next=q.next;
}
return res.next;
}
}
解法一:递归
这个解法太牛逼了……我有点懵。
public ListNode deleteNode(ListNode head, int val) {
if (head == null)
return head;
if (head.val == val)
return head.next;
head.next = deleteNode(head.next, val);
return head;
}