Remove Nth Node From End of List, Leetcode 解题笔记

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.
Note:
Given n will always be valid.
Try to do this in one pass.

要求只扫一遍list解决问题,自然而然的想到了two pointer的方法,一个在另一个前面n的位置,两个同时同速向尾部移动,当前面的pointer到达尾部时,后面的pointer正好在距离尾部n的位置。算法很简单,但是难点在于对node的处理,尤其要注意需要移除第一个(head)node的时候的处理问题,可以用一个holder来指向head,使得head不再是第一个node。
面试中遇到这种问题不要急躁,因为总体代码比较短,可以先把大概代码写出来,然后用几个edge cases来测试完善,不用要求自己必须一开始就全写对。

/**
 * 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) {
        if(head == null) return null;
        
        ListNode hold = new ListNode(0);
        hold.next = head;
        ListNode slow = hold;
        ListNode fast = head;
        for(int i = 0; i < n; i++){
            fast = fast.next;
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return hold.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s