码迷,mamicode.com
首页 > 编程语言 > 详细

Remove Nth Node From End of List LeetCode Java

时间:2018-06-09 22:04:32      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:nod   link   end   example   move   etc   tco   fast   color   

描述
Given a linked list, remove the n
th node from the end of list and return its head.
For example, Given linked list: 1->2->3->4->5, and n = 2.
Aer 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.
分析
代码

 1 public static ListNode removeNthNodeFromEnd(ListNode head, int n) {
 2         if (head == null || n == 0)
 3             return head;
 4         ListNode fast = head, slow = head, p = head;
 5         int len = 1;
 6         while (p.next != null) {
 7             p = p.next;
 8             len++;
 9         }
10         if (n == len) {
11             return head.next;
12         }
13         n = n % len;
14         for (int i = 0; i < len - n - 1; i++) {
15             fast = fast.next; // fast会比i多进1
16         }
17         slow = fast.next;
18         fast.next = slow.next;
19         return head;
20     }

 

Remove Nth Node From End of List LeetCode Java

标签:nod   link   end   example   move   etc   tco   fast   color   

原文地址:https://www.cnblogs.com/ncznx/p/9160875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!