LintCode之链表倒数第n个节点

题目描述:

 

我的代码:

 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个节点了。

posted @ 2017-10-26 18:48  zwt3  阅读(156)  评论(0编辑  收藏  举报