首页 > 其他 > 详细

Remove Nth Node From End of List

时间:2014-10-27 00:18:37      阅读:311      评论:0      收藏: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;
        }
    }
}

 

Remove Nth Node From End of List

原文:http://www.cnblogs.com/bluedreamviwer/p/4052962.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!