leetcode:Nth to Last Node in List

1、

Find the nth to last element of a singly linked list. 

The minimum number of nodes in list is n.

Given a List  3->2->1->5->null and n = 2, return node  whose value is 1.

2、

  1、由于链表没有得到长度的值,只能通过一个一个移来进行判断

  2、先移n位,原来的再移length-n位既可以

3、代码:

  

 ListNode nthToLast(ListNode head, int n) {
            if (head == null || n < 1) {
                return null;
            }
        // 3->2->1->5->7->9->9->null,n=2,  1
            /**
             * 1、7大小,最后两位
             * 2、先已两位,然后停止
             * 3、一起再移余下的位数,那么原来的就变成倒数2为
             */
            ListNode p1 = head;
            ListNode p2 = head;
            for (int j = 0; j < n - 1; ++j) {
                if (p2 == null) {
                    return null;
                }
                p2 = p2.next;
            }
            while (p2.next != null) {   
                p1 = p1.next;   
                p2 = p2.next;
            }
            return p1;
        }

 

posted @ 2016-03-29 15:52  自朗活  阅读(166)  评论(0编辑  收藏  举报