首页 > 其他 > 详细

[leetcode]19. Remove Nth Node From End of List删除链表倒数第N个节点

时间:2019-04-05 17:23:13      阅读:144      评论:0      收藏:0      [点我收藏+]

Given a linked list, remove the n-th node from the end of list and return its head.

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.

 

Follow up:

Could you do this in one pass?

 

题意: 删除链表倒数第N个节点

 

Solution1: Two Pointers(fast and slow)

1. Let fast pointer to move n steps in advance, making sure there is n steps gap between fast and slow 

2. Move fast and slow pointer together until fast.next == null

技术分享图片

 

技术分享图片

 

code

 1 /*
 2 Time: O(n)
 3 Space: O(1)
 4 */
 5 class Solution {
 6       public ListNode removeNthFromEnd(ListNode head, int n) {
 7         ListNode dummy = new ListNode(-1);
 8         dummy.next = head;
 9         ListNode slow = dummy, fast = dummy;
10 
11         for (int i = 0; i < n; i++)  // fast先走n步
12             fast = fast.next;
13 
14         while(fast.next != null) { // fast和slow一起走
15             slow = slow.next;
16             fast = fast.next;
17         }
18         //直接避开要删除的节点
19         slow.next = slow.next.next;
20         return dummy.next;
21     }
22 }

 

[leetcode]19. Remove Nth Node From End of List删除链表倒数第N个节点

原文:https://www.cnblogs.com/liuliu5151/p/10659178.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!