LintCode Nth to Last Node in List 链表倒数第n个节点

来源:互联网 发布:linux中rpm命令 编辑:程序博客网 时间:2024/05/22 07:43

找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点1.

Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.
Example
Given a List 3->2->1->5->null and n = 2, return node whose value is 1.

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @param n: An integer.     * @return: Nth to last node of a singly linked list.      */    ListNode nthToLast(ListNode head, int n) {        ListNode p = head, q = head;        while(n > 0 && p != null) {            p = p.next;            n--;        }        while(p != null) {            q = q.next;            p = p.next;        }        return q;    }}
0 0
原创粉丝点击