首页 > 编程语言 > 详细

Remove Nth Node From End of List LeetCode Java

时间:2018-06-09 21:44:19      阅读:160      评论:0      收藏:0      [点我收藏+]

描述
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

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

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