剑指offer-链表中倒数第k个结点

2016/05/24 C和C++基础

题目描述

输入一个链表,输出该链表中倒数第k个结点。

#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
    	vector<ListNode*> vec;
        while(pListHead!=NULL){
            vec.push_back(pListHead);
            pListHead=pListHead->next;
        }
        int len=vec.size();
        if(len>=k)
        	return vec[len-k];
        else
            return NULL;
    }
};

Search

    Post Directory