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

Leetcode19 Remove Nth Node From End of List

时间:2018-12-10 14:01:08      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:for   previous   n+1   class   null   tno   col   efi   lis   

开始没思路,看了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答案写的一样…

Leetcode19 Remove Nth Node From End of List

标签:for   previous   n+1   class   null   tno   col   efi   lis   

原文地址:https://www.cnblogs.com/chason95/p/10095404.html

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