您的位置:首页 > 其它

从尾到头打印链表

2016-06-24 00:23 302 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息