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

Remove Nth Node From End of List

时间:2016-07-03 06:56:13      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

 Notice

The minimum number of nodes in list is n.

Example

Given linked list: 1->2->3->4->5->null, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5->null.

Challenge 

Can you do it without getting the length of the linked list?

分析:

为何删除倒数第n个node,我们需要找到那个node的parent,然后parent.next = parent.next.next. 这里我们创建一个dummy node用来处理删除的是第一个node的情况。

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param head: The first node of linked list.
15      * @param n: An integer.
16      * @return: The head of linked list.
17      */
18     ListNode removeNthFromEnd(ListNode head, int n) {
19         ListNode dummyNode = new ListNode(0);
20         dummyNode.next = head;
21         
22         int size = size(dummyNode);
23         if (n + 1 > size) return dummyNode.next;
24         // get parent node
25         ListNode parent = dummyNode;
26         int kth = size - n;
27         
28         int count = 1;
29         while (count < kth) {
30             parent = parent.next;
31             count++;
32         }
33        
34         parent.next = parent.next.next;
35         return dummyNode.next;
36     }
37     
38     public int size(ListNode head) {
39         int size = 0;
40         while (head != null) {
41             size++;
42             head = head.next;
43         }
44         return size;
45     }
46 }

如果我们不允许得到list 的长度,我们可以用下面的方法。

 1 public class Solution {
 2     public ListNode removeNthFromEnd(ListNode head, int n) {
 3         if (n <= 0) return null;
 4         
 5         ListNode dummy = new ListNode(0);
 6         dummy.next = head;
 7         
 8         ListNode parent = dummy;
 9         for (int i = 0; i < n; i++) {
10             if (head == null) {
11                 return null;
12             }
13             head = head.next;
14         }
15         while (head != null) {
16             head = head.next;
17             parent = parent.next;
18         }
19         parent.next = parent.next.next;
20         return dummy.next;
21     }
22 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5636454.html

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