首页 > 代码库 > 19. Remove Nth Node From End of List
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。