首页 > 其他 > 详细

LintCode之链表倒数第n个节点

时间:2017-10-26 19:39:44      阅读:258      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享

 

我的代码:

 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 
13 
14 public class Solution {
15     /*
16      * @param head: The first node of linked list.
17      * @param n: An integer
18      * @return: Nth to last node of a singly linked list. 
19      */
20     public ListNode nthToLast(ListNode head, int n) {
21         // write your code here
22         if(head == null) {
23             return null;
24         }
25         ListNode h = new ListNode(-1);
26         //倒置单链表
27         while(head != null) {
28             ListNode node = new ListNode(head.val);
29             if(h.next == null) {
30                 h.next = node;
31             }else {
32                 node.next = h.next;
33                 h.next = node;
34             }
35             if(head.next != null) {
36                 head = head.next;
37             }else {
38                 head = null;
39             }
40         }
41         h = h.next;
42         //取得倒置后的单链表的第n个节点,这个节点就是原链表的倒数第n个节点
43         for(int i=1; i<n; i++) {
44             h = h.next;
45         }
46         ListNode node = new ListNode(h.val);
47         return node;
48     }
49 }

 

总结:因为这是单链表,无法像双链表一样轻松的获得一个节点的前一个节点,所以,我就把这个单链表倒置,倒置后的单链表的第n个节点就是倒置前的单链表的倒数第n个节点,这样就能通过遍历获得倒数第n个节点了。

LintCode之链表倒数第n个节点

原文:http://www.cnblogs.com/zwxblog/p/7738411.html

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