N nodes penultimate question 19, delete the list

I, entitled 1

Here Insert Picture Description

Second, the idea

The first n nodes of the current node cycle stored, processed directly after traversal completion.

Note: 1, the length is 0, 1; 2, the first node is deleted, the last, second, penultimate; handling special.

Third, the code

public class T0019 {

    public static void main(String[] args) {

        int[] nums = {1,2,3,4,5};
//        int[] nums = {1};

        ListNode head = new ListNode(nums[0]);
        ListNode node = head;

        for ( int i = 1; i < nums.length; i++ ){
            node.next = new ListNode(nums[i]);
            node = node.next;
        }

        node = removeNthFromEnd( head, 5);

        while ( node != null ){
            System.out.println(node.val);
            node = node.next;
        }

    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {

        //对一个不删除,输入为空,只输入一个节点的情况进行处理
        if ( n == 0 || head == null )
            return head;
        else if ( head.next == null )
            return null;
        
        ListNode node = head;           //用于迭代
        ListNode bfRemove = head;       //存储当前迭代的节点的前n个节点

        int count = 0;                  //当前是第几个节点了
        while ( node != null ){
            count++;
            
            //在当前节点有前n个节点之时对bfRemove进行迭代
            if ( count > n+1 ){
                bfRemove = bfRemove.next;
            }
            node = node.next;

        }
//        System.out.println( bfRemove.val  + "\t" + count);
        
        //对删除的节点是头结点这种特殊情况的处理
        if ( count == n ){
            bfRemove.val = bfRemove.next.val;
        }

        bfRemove.next = bfRemove.next.next;

        return head;
    }
}

//Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

  1. Source: stay button (LeetCode)
    link: https: //leetcode-cn.com/problems/remove-nth-node-from-end-of-list
    copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. ↩︎

Published 48 original articles · won praise 1 · views 850

Guess you like

Origin blog.csdn.net/weixin_45980031/article/details/104172735