从尾到头打印链表

来源:互联网 发布:铭万网络到底有多差 编辑:程序博客网 时间:2024/05/16 14:23
#define  _CRT_SECURE_NO_WARNINGS#include<iostream>using namespace std;#include<stack>struct ListNode{    int _value;    ListNode* _next;    ListNode(int value)        :_value(value),        _next(NULL)    {}};class List{    typedef ListNode Node;public:    List()        :_head(NULL)    {}    void Insert(const int value)    {        Node *tmp = new Node(value);        if (_head == NULL)        {            _head = tmp;        }        else        {            Node* cur = _head;            while (cur->_next)            {                cur = cur->_next;            }            cur->_next = tmp;        }    }    void PrintTailToHead() //利用栈实现    {        stack<Node*> s;        Node* cur = _head;        while (cur)        {            s.push(cur);            cur = cur->_next;        }        while (!s.empty())        {            Node * tmp = s.top();            cout << tmp->_value << " ";            s.pop();        }    }    void PrintTailToHeadRecur()//利用递归实现    {        _PrintTailToHeadRecur(_head);    }protected:    void _PrintTailToHeadRecur(Node* head)    {        if (head)        {            if (head->_next)            {                _PrintTailToHeadRecur(head->_next);            }        }        cout << head->_value << " ";    }private:    Node* _head;};void test(){    List L;    L.Insert(1);    L.Insert(2);    L.Insert(3);    L.Insert(4);    L.Insert(5);    L.PrintTailToHead();    cout << endl;    L.PrintTailToHeadRecur();}int main(){    test();    system("pause");    return 0;}
0 0
原创粉丝点击