本文共 1518 字,大约阅读时间需要 5 分钟。
#define _CRT_SECURE_NO_WARNINGS#includeusing namespace std;#include 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 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;}
转载地址:http://fqstd.baihongyu.com/