从尾到头打印单链表
PS:
如果题设不要求不能改变链表结构时,可以使用单链表的逆置(之前已经写过),单链表的逆置改变了链表的方向,严格要求时不能这样写。
解1:递归求解
//从尾到头打印单链表--递归实现
ListNode* PrintList(ListNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}
ListNode* cur = pHead;
if (cur->_next != NULL)
{
PrintList(cur->_next);
}
cout << cur->_value << "->";
}
int main()
{
ListNode* pHead = new ListNode(1);
ListNode* cur = pHead;
ListNode* p = pHead;
for (int i = 2; i <= 10; ++i)
{
ListNode* temp = new ListNode(i);
cur->_next = temp;
cur = temp;
}
PrintList(pHead);
system("pause");
return 0;
}
解2:非递归实现---利用栈的特性:先进的后出
ListNode* PrintList(ListNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}
ListNode* p = pHead;
stack<ListNode*> q; //一个元素类型为ListNode* 的栈
while (p)
{
q.push(p);
p = p->_next;
}
while (q.size())
{
cout << q.top()->_value << "->";
q.pop();
}
}
int main()
{
ListNode* pHead = new ListNode(1);
ListNode* cur = pHead;
ListNode* p = pHead;
for (int i = 2; i <= 10; ++i)
{
ListNode* temp = new ListNode(i);
cur->_next = temp;
cur = temp;
}
PrintList(pHead);
system("pause");
return 0;
}
在线编译代码: 利用vector
//从尾到头打印单链表
#include <iostream>
#include <stack>
#include <vector>
#include <Windows.h>
using namespace std;
struct ListNode
{
int _value;
ListNode* _next;
ListNode(const int& value)
:_value(value)
, _next(NULL)
{}
};
vector<int> Print(ListNode* head)
{
vector<int> tty;
stack<int> zzp;
ListNode* p = head;
while (p != NULL)
{
zzp.push(p->_value);
p = p->_next;
}
while (!zzp.empty())
{
tty.push_back(zzp.top());
zzp.pop();
}
return tty;
}
int main()
{
ListNode* head = new ListNode(1);
ListNode* p = head;
ListNode* cur = head;
for (int i = 2; i <= 10; ++i)
{
ListNode* temp = new ListNode(i);
cur->_next = temp;
cur = temp;
}
while (p)
{
cout << p->_value << "->";
p = p->_next;
}
cout << endl;
vector<int> cc = Print(head);
for (int j = 0; j < cc.size(); ++j)
{
cout << cc[j] << "->";
}
system("pause");
return 0;