166. 链表倒数第n个节点

166. 链表倒数第n个节点
 

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

Example 1:
    Input: list = 3->2->1->5->null, n = 2
    Output: 1


Example 2:
    Input: list  = 1->2->3->null, n = 3
    Output: 1

ListNode * nthToLast(ListNode * head, int n) {
        // write your code here
        if(nullptr == head)
            return nullptr;
        std::vector<ListNode*>vec ;
        while(head)
        {
            vec.push_back(head);
            head = head->next;
        }
        return vec[vec.size() -n ];
    }

猜你喜欢

转载自blog.csdn.net/yinhua405/article/details/111879510