您的位置:首页 > Web前端 > Node.js

leetcode Remove Nth Node From End of List

2015-03-04 14:54 288 查看
双指针大法又显神通。

/**
* Definiti
4000
on for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null)return null;
ListNode ret=new ListNode(-1);
ret.next=head;
ListNode p1=ret;
ListNode p2=ret;
int i=0;
while(i<n&&p2.next!=null){
p2=p2.next;
i++;
}
if(p2==null&&i!=n)return head;

while(p2.next!=null){
p1=p1.next;
p2=p2.next;

}
p1.next=p1.next.next;
return ret.next;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: