Title: Given A linked list, remove the nth node from the end of the list and return its head.
For example,
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.
test instructions and analysis: The first thing I do is to iterate through the length, then the length minus n will know to delete the positive number of elements, not meet the requirements, because only one time, so only with two pointers, a fast pointer to go first n step, a slow pointer from the beginning, so when the fast pointer to the tail, The slow pointer refers to the first element of the element to be deleted.
Code:
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/classSolution { PublicListNode Removenthfromend (ListNode head,intN) {if(Head = =NULL)return NULL; ListNode Fast= head;//because it can only be traversed once, so can only use two pointers, a fast pointer to go first n, a slow pointer from the beginning, so when the fast pointer to the tail, the slow pointer is to delete the element's previous element. ListNode low =Head; for(inti=0;i<n;i++) {Fast=Fast.next; } if(Fast = =NULL) {Head=Head.next; returnHead; } while(Fast.next! =NULL) { low=Low.next; Fast=Fast.next; } Low.next=Low.next.next; returnHead; }}
[Leetcode] 19. Remove Nth Node from End of List Java