LeetCode


题目:

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

}

}

 

本站声明
本文转载自:http://www.cnblogs.com/shuaiwhu/p/5060233.html     作者:Remove Nth Node From End of List - NULL00     发布日期:2015/12/20     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号