19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

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 will always be valid.

Follow up:

Could you do this in one pass?

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         System.out.println(head.val);
12         if (head == null || head.next == null) return null;
13         
14         ListNode p1 = head;
15         for (int i = 0; i < n; ++i) {
16            
17             p1 = p1.next;
18         }
19         if (p1 == null) return head.next;
20         
21         ListNode p2;
22         for (p2 = head; p1.next != null; p1 = p1.next) {
23             p2 = p2.next;
24         }
25         p2.next = p2.next.next;
26         return head;
27     }
28 }
原文地址:https://www.cnblogs.com/hyxsolitude/p/12304800.html