题目链接: https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/

题目解析
使用双指针。遍历记录pre
和cur
当前节点,同时判断当前val
是否匹配,如果匹配就跳出循环。
public ListNode deleteNode(ListNode head, int val) {
if (head.val == val) return head.next;
ListNode pre=head,cur = head.next;
while (cur!=null && cur.val != val){
pre = cur;
cur = cur.next;
}
if (cur!=null) pre.next = cur.next;
return head;
}
复杂度分析
空间复杂度: O(1)。
时间复杂度: O(N)。
网友评论