首页 > 其他 > 详细

[leedcode 19]Remove Nth Node From End of List

时间:2015-07-07 16:17:22      阅读:159      评论:0      收藏:0      [点我收藏+]

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.


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //题眼:两个指针,一快一慢,步长为n
        //注意几点:
        //1.判断输入的整数范围
        //2.删除的是头结点的处理方式(画图)
        
        if(n<=0)return null;
        ListNode right=head;
        while(n>0){
            right=right.next;
            n--;
        }
        ListNode left=head;
        if(right==null)return head.next;//注意删除第一个节点的例外
        while(right.next!=null){
            left=left.next;
            right=right.next;
        }
        left.next=left.next.next;//删除节点
         return head;
        
    }
}

 

[leedcode 19]Remove Nth Node From End of List

原文:http://www.cnblogs.com/qiaomu/p/4627193.html

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