题目:
Given a linked list, remove the nth node from the end of 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 will always be valid.
Try to do this in one pass.
思路:
三个指针p1,p2,p3,让第一指针p1走n - 1步停下来,然后p1和p2一起往前走,同时保持一个指针指向p2的前一个节点。
package list; public class RemoveNthNodeFromEndOfList { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode p1 = head; ListNode p2 = head; ListNode prevp2 = new ListNode(0); prevp2.next = p2; head = prevp2; while (--n > 0) { p1 = p1.next; } while (p1.next != null) { p1 = p1.next; prevp2 = p2; p2 = p2.next; } prevp2.next = p2.next; return head.next; } public static void main(String[] args) { // TODO Auto-generated method stub } }