【剑指Offer 18】删除链表的节点

/**
 * 剑指 Offer 18. 删除链表的节点
 * https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/
 *
 * 思路:双指针
 * */
public class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        ListNode prev = null;
        ListNode next = head;
        while (next != null) {
            if (next.val == val) {
                if (next == head) {
                    head = head.next;
                } else {
                    prev.next = next.next;
                }
                break;
            }
            prev = next;
            next = next.next;
        }
        return head;
    }
}
posted @ 2022-06-26 19:53  廖子博  阅读(13)  评论(0编辑  收藏  举报