码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Nth Node From End of List 解答

时间:2015-09-16 07:30:09      阅读:141      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!