题目:

链表倒数第n个节点

找到单链表倒数第n个节点,保证链表中节点的最少数量为n。

样例

给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.

解题:

某年408计算机考研题目

Java程序:

/**
 * 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) {
        // write your code here
        if(head ==null)
            return null;
        if( head.next ==null && n==1)
            return head;
        ListNode p = head;
        ListNode current = new ListNode(0);
        current.next = head;
        while( p.next!=null){
            if(n>1){
                p = p.next;
                n --;
            }else{
                p = p.next;
                current = current.next;
                
            }
        }
        return current.next;
    }
}
View Code

总耗时: 2548 ms

Python程序: