首页 > 其他 > 详细

[lintcode easy]Remove Nth Node From End of List

时间:2015-11-25 06:36:55      阅读:290      评论:0      收藏:0      [点我收藏+]

Remove Nth Node From End of List

 

Given a linked list, remove the nth node from the end of list and return its head.

 
 
Example

Given linked list: 1->2->3->4->5->null, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5->null.
Note

The minimum number of nodes in list is n.

Challenge

O(n) time

 

////same as return Nth Node to End

////Using two pointer to track node, keep their distance as N step.

///If n is the the first node, return head.next;  else ,return head;

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        if(head==null || n<0) return head;
        ListNode fast=head;
        ListNode slow=new ListNode(0);
        slow.next=head;
        
        while(n--!=0)
        {
            fast=fast.next;
        }
        if(fast==null)
        {
            return head.next;
        }
        while(fast!=null)
        {
            fast=fast.next;
            slow=slow.next;
            
        }
        
        ListNode next=slow.next;
        slow.next=next.next;
        
        return head;
    }
}

 

[lintcode easy]Remove Nth Node From End of List

原文:http://www.cnblogs.com/kittyamin/p/4993474.html

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