标签:remove problems example next new 运行时间 one pass http com
题目:
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
标签:remove problems example next new 运行时间 one pass http com
原文地址:http://www.cnblogs.com/panini/p/6698135.html