您的位置:首页 > Web前端 > Node.js

19. Remove Nth Node From End of List

2018-03-11 10:50 375 查看

关于链表尾部节点的问题可以考虑快慢节点的方法解决。
public ListNode removeNthFromEnd(ListNode head, int n) {
   
    ListNode start = new ListNode(0);
    ListNode slow = start, fast = start;
    slow.next = head;
   
    //Move fast in front so that the gap between slow and fast becomes n
    for(int i=1; i<=n+1; i++)   {
        fast = fast.next;
    }
    //Move fast to the end, maintaining the gap
    while(fast != null) {
        slow = slow.next;
        fast = fast.next;
    }
    //Skip the desired node
    slow.next = slow.next.next;
    return start.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: