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

来源:互联网 发布:学校网络舆情自查报告 编辑:程序博客网 时间:2024/05/23 10:21
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(nullptr==pListHead)
            return pListHead;
          if(k==0)
            return nullptr;
    stack<ListNode *>  tree;
        ListNode *p=pListHead;
        while(p!=NULL)
        { tree.push(p);p=p->next;}
      
        for(int i=1;i<k;i++)
        {
            
            tree.pop();
            if(tree.empty())
                return nullptr;
        }
        return tree.top();
    }
};
0 0
原创粉丝点击