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/

转载于:https://www.cnblogs.com/panini/p/6698135.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值