Leetcode 19.Remove Nth node from End of List (delete the last nth node) thinking and method of solving problems

Source: Internet
Author: User

Remove Nth Node from End of List


Given A linked list, remove the nth node from the end of the list and return its head.

For example,

Given linked list:1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.

Try to do the in one pass.


Idea: Delete the last nth node, because it is a single linked list, do not know the total number of nodes, it is first to traverse, count the total number of nodes, calculate the first number of positive numbers, and then delete.

The algorithm is simple and the code is as follows:

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    ListNode removenthfromend (listnode head, int n) {        //delete the last nth        if (n = = 0) {            return head;        }        int nth = 0;//the penultimate nth        int count = 0;//Total number of nodes        listnode p = head;        Statistics Count        while (P! = null) {            p = p.next;            count++;        }        Calculates the value of the positive n, calculated from 0        n = count-n;        if (n = = 0) {//If 0, the header node, return to the head node next can            return head.next;        }        p = head;        Count to N-1, then make n-1.next = N.next = N-1.next.next        while (Nth < n-1) {            p = p.next;            nth++;        }        P.next = P.next.next;        return head;    }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 19.Remove Nth node from End of List (delete the last nth node) ideas and methods of solving problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.