题目
题解
双指针pre和cur,pre用来指向当前cur结点的前一个结点,当找到val值的节点就丢弃cur节点让pre.next = cur.next.
/**
* 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 || (head.val == val && head.next == null)){
return null;
}
if(head.val == val){
return head.next;
}
ListNode pre = head;
ListNode cur = head.next;
while(cur != null){
if(cur.val == val){
pre.next = cur.next;
break;
}
pre = cur;
cur = cur.next;
}
return head;
}
}