导航

Remove Nth Node From End of List

Posted on 2014-10-26 22:44  八竿子打不着  阅读(100)  评论(0)    收藏  举报

需要额外添加两个相距为n的节点,遍历一遍之后就可以得到结果。

/**
 * Definition 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) {
        ListNode p=head;
        ListNode ne=head;
        int i=0;
        while(ne.next!=null){
            ne=ne.next;
            if(i>=n){
                p=p.next;
            }
            i++;
        }
        if(i==0){
            return null;
        }
        else if(i+1==n){
            return head.next;
        }
        else{
            p.next=p.next.next;
            return head;
        }
    }
}