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

[leetcode] 19. Remove Nth Node From End of List (Medium)

时间:2018-11-13 16:08:56      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:ref   nth node   node   pre   run   str   list   节点   索引   

原题链接

删除单向链表的倒数第n个结点。

思路:
用两个索引一前一后,同时遍历,当后一个索引值为null时,此时前一个索引表示的节点即为要删除的节点。
Runtime: 13 ms, faster than 24.49% of Java

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow=head;
        ListNode fast=head;
        for(int i=0;i<n;i++)
            fast=fast.next;
        if (fast==null){
            return head.next;
        }
        while(fast.next!=null)
        {
            slow=slow.next;
            fast=fast.next;
        }
        slow.next=slow.next.next;
        return head;
    }
}

[leetcode] 19. Remove Nth Node From End of List (Medium)

标签:ref   nth node   node   pre   run   str   list   节点   索引   

原文地址:https://www.cnblogs.com/ruoh3kou/p/9952478.html

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