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

remove-nth-node-from-end-of-list

时间:2017-12-10 21:23:30      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:操作   color   好的   com   pass   返回   one   ali   循环   

题目:

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.

   After 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 /*
 2 class ListNode{
 3      int val;
 4      ListNode next;
 5      ListNode(int x) {
 6          val = x;
 7          next = null;
 8      }
 9 }
10 */
11 public class Solution {
12     public ListNode removeNthFromEnd(ListNode head, int n){
13     /*
14     如果head为空,那么很明显会返回为空。
15     */
16         if(head == null)
17         {
18             return null;
19         }
20     /*
21     如果n为0或者n小于0,可以举例说明返回的是原链表
22     */
23         if(n == 0 || n < 0)
24         {
25             return head;
26         }
27     /*
28     下面的循环是计算该链表的长度
29     */
30         int len = 0;
31         ListNode node = head;
32         while(node != null)
33         {
34             len = len+1;
35             node = node.next;
36         }
37     /*
38     接下来我们定义一个新的节点,用于指向新的链表。
39 
40     下面是本题的主题:我们分两种情况进行讨论,第一种情况就是当n在(0,len)之间,
41     我们的解题思路如下:
42     首先我们找到倒数第n个节点的前一个节点,而后我们利用链表的删除操作将倒数第n个节点删除。
43     第二种情况就是当n>= len的情况,其实这种情况的思路和前面介绍的思路是一样的。
44     */
45         ListNode pHead = new ListNode(-1);
46         if(n >= len)
47         {
48             pHead.next = head;
49             int m = n%len;
50             if(m == 0)
51             {
52                 pHead.next = head.next;
53                 head = null;
54             }else
55             {
56                 node = head;
57                 pHead.next = head;
58             
59                 for(int i = 1;i < len-m;i++)
60                 {
61                     node = node.next;
62                 }
63                 ListNode current1 = node.next;
64                    node.next = current1.next;
65             }
66         }else if(n >0 && n <len)
67         {
68             
69             node = head;
70             pHead.next = head;
71             
72             for(int i = 1;i < len-n;i++)
73             {
74                 node = node.next;
75             }
76             System.out.println(node.val);
77             ListNode current = node.next;
78             node.next = current.next;
79         }
80         return pHead.next;
81     }
82 }

至此,我们已经完成了本题的讲解,如果有更好的方法,欢迎联系我,邮箱:cmhhw_xju@163.com qq:764666877

 

remove-nth-node-from-end-of-list

标签:操作   color   好的   com   pass   返回   one   ali   循环   

原文地址:http://www.cnblogs.com/cmh-hw/p/8017977.html

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