Topic
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Answer
Using the idea of quick and slow pointers, the fast hands go first n steps, then go at the same time and stop at the end of the pointer. Note that the processing of the head node, such as 1->2->null, n=2, returns 2->NULL, the code is as follows:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {* val = x; * next = null; *< c5/>} *} */public class Solution {public ListNode removenthfromend (listnode head, int n) { if (head==null) { R Eturn head; } ListNode Fast=head; ListNode Slow=head; while (n-->0) { fast=fast.next; } if (fast==null) { //Determine if fast is at the end of the return slow.next; } while (fast.next!=null) {//note here, fast must not be null, so the previous case of NULL is Fast=fast.next; Slow=slow.next; } Slow.next=slow.next.next; return head; }}
---EOF---
Leetcode Remove Nth Node from End of List