/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ classSolution{ public ListNode deleteNode(ListNode head, int val){ if(head.val==val) return head.next; ListNode pre=head; ListNode cur=head.next; while(cur!=null&&cur.val!=val){ pre=cur; cur=cur.next; } if(cur!=null){ pre.next=cur.next; } return head;
} }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defdeleteNode(self, head: ListNode, val: int) -> ListNode: if head.val==val: return head.next pre=head cur=head.next while cur and cur.val!=val: pre=cur cur=cur.next if cur: pre.next=cur.next return head