LintCode 链表倒数第n个节点

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

样例

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

分析:设两个指针 p1和p2,p1遍历到n-1的位置,p2从头开始遍历 当p1到链表尾部的时候,p2刚好到倒数n的位置 

        注意鲁棒性的考虑

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @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||n==0)
        return NULL;
        
        ListNode *p1=head;
        ListNode *p2=NULL;
        for(int i=0;i<n-1;i++)
        {
            if(p1->next!=NULL)
            {
                p1=p1->next;
            }
            else
            return NULL;
        }
        p2=head;
        while(p1->next!=NULL)
        {
            p1=p1->next;
            p2=p2->next;
        }
        return p2;
    }
};

  

原文地址:https://www.cnblogs.com/lelelelele/p/6116938.html