剣はオファー18を指します。リンクリストのノードを削除します

剣はオファー18を指します。リンクリストのノードを削除します

タイトル説明

ここに画像の説明を挿入

問題解決のアイデア

ダブルポインタ

/**
 * 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) return head.next;
        //双指针
        ListNode pre = head, cur = head.next;

        while (cur != null && cur.val != val) {
    
    
            pre = pre.next;
            cur = cur.next;
        }
        if (cur != null) {
    
    
            pre.next = cur.next;
        }
        return head;
    }
}

おすすめ

転載: blog.csdn.net/cys975900334/article/details/114933762