Java deletes the last nth node of the linked list and returns the head pointer of the linked list

Title description

Given a linked list, delete the nth node from the bottom of the linked list and return the head pointer of the linked list.
For example,

The given linked list is: 1->2->3->4->5, n= 2.After 
 deleting the nth node from the bottom of the linked list, the linked list becomes 1->2->3->5.

Remarks:

The question guarantees that n must be valid.
Please provide an algorithm with a time complexity of \ O(n) O(n)

 

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        int len = 0;
        ListNode curNode = head;
        while(curNode!=null){
            len++;
            curNode = curNode.next;
        }
        
        //如果要删除逆向的n位置 是链表的头节点 直接返回next节点 如:{1,2} n=2 直接返回2
        if(len == n){
            return head.next;
        }
        
        //正向顺序 被删除节点的前一个节点
        int targetPos = len - n;
        
        int tmpPos = 0;
        ListNode tmpNode = head;
        while(tmpNode!=null){
            tmpPos++;
            //正向顺序 被删除节点的前一个节点
            if(tmpPos == targetPos){
                tmpNode.next = tmpNode.next.next;
                break;
            }
            tmpNode = tmpNode.next;
        }
        
        return head;
    }
}

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112717294