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