码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Remove Nth Node from End of List

时间:2016-03-06 11:18:00      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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

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.
 
因为要删除的节点可能是head,所以要使用一个fakehead
/**
 * 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
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        ListNode fast = fakehead;
        for(int i = 0; i <= n; i++)
            fast = fast.next;
        
        ListNode slow = fakehead;
        while(fast != null){
            slow = slow.next;
            fast = fast.next;
        }
        
        slow.next = slow.next.next;
        return fakehead.next;
    }
}

 

lintcode-easy-Remove Nth Node from End of List

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5246616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!