首页 > 其他 > 详细

Remove Nth Node From End of List 解答

时间:2015-09-16 07:27:15      阅读:226      评论:0      收藏:0      [点我收藏+]

Question

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.

Solution -- One pass

Use two pointers, slow and fast. Fast pointer firstly move n steps. Then, when fast pointer reaches end, slow pointer reaches the node before deleted node.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         ListNode fast = head, slow = head;
12         if (head == null)
13             return head;
14         while (n > 0) {
15             fast = fast.next;
16             n--;
17         }
18         // If remove the first node
19         if (fast == null) {
20             head = head.next;
21             return head;
22         }
23         while (fast.next != null) {
24             fast = fast.next;
25             slow = slow.next;
26         }
27         slow.next = slow.next.next;
28         return head;
29     }
30 }

 

Remove Nth Node From End of List 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4812038.html

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