代码
/**
* 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.val==val){
head=head.next;
return head;
}
ListNode t=head;
//找到要删除的节点的,前一个结点
while(t.next.val!=val){
t=t.next;
}
t.next=t.next.next;
return head;
}
}
结果
二刷代码
/**
* 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 null;
if(head.val==val)
return head.next;
ListNode cur=head;
ListNode pre=null;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
break;
}
pre=cur;
cur=cur.next;
}
return head;
}
}