19. Remove Nth Node From End of List
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19. Remove Nth Node From End of List相关的知识,希望对你有一定的参考价值。
题目:
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.
链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description
4/11/2017
87%, 14ms
要了解每个变量的意义,想不出来就画图,不要猜初始值定在哪里
fast也可以设在dummy上,这样第8,12行就按照fast.next来判断,不过运行时间会加到18ms
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 if (head == null || n <= 0) return head; 4 ListNode dummy = new ListNode(-1); 5 dummy.next = head; 6 ListNode fast = head; 7 ListNode slow = dummy; 8 while (n > 0 && fast != null) { 9 fast = fast.next; 10 n--; 11 } 12 while (fast != null) { 13 fast = fast.next; 14 slow = slow.next; 15 } 16 slow.next = slow.next.next; 17 return dummy.next; 18 } 19 }
官方解答
https://leetcode.com/articles/remove-nth-node-end-list/
以上是关于19. Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章
LC_19. Remove Nth Node From End of List
19. Remove Nth Node From End of List
19. Remove Nth Node From End of List
19. Remove Nth Node From End of List