Leetcode19 Remove Nth Node From End of List

开始没思路,看了Solution自己写的:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode head_previous = new ListNode(0);
        head_previous.next = head;
        ListNode fast = head_previous,slow = head_previous;
        //fast first to move
        for(int i=0;i<n+1;i++){
            fast = fast.next;
        }
        //now the gap between fast and slow is n+1,maintain it
        while(fast!=null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head_previous.next;
    }
}

9ms,51.75%

可以了,因为和6ms答案写的一样…

posted @ 2019-03-21 20:06  大胖子球花  阅读(73)  评论(0)    收藏  举报