# 面试题8：从尾到头打印单链表,

```/*     用栈实现从尾到头打印单链表    */
{
stack<int> s;
while(head != NULL && p != NULL)   //入栈
{
s.push(p->data);
p = p->next;
}

while(! s.empty())  //出栈
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
}```

```/*     用递归实现从尾到头打印单链表    */
{
Node *p;

return;
else
{
cout << p->data <<" ";
}
}```

```#include<iostream>
#include <stack>
#include<stdlib.h>
#include<time.h>

using namespace std;

typedef struct node
{
int data;
struct node *next;
}Node;

/*     创建含有n个结点的单链表    */
{

/* 初始化随机数种子 */
srand(time(0));  //srand函数在stdlib.h头文件中，time函数在time.h头文件中

for(int i=0; i < n; i++)
{
Node *p = (Node *)malloc(sizeof(Node));
p->data = rand()%100+1;  //随机生成100以内的数字
p->next = q->next;
q->next = p;
q = p;
}
q->next = NULL;

}
/*     用栈实现从尾到头打印单链表    */
{
stack<int> s;
while(head != NULL && p != NULL)   //入栈
{
s.push(p->data);
p = p->next;
}

while(! s.empty())  //出栈
{
cout << s.top() << " ";
s.pop();
}

cout << endl;
}

/*     用递归实现从尾到头打印单链表    */
{
Node *p;

return;
else
{
cout << p->data <<" ";
}
}

/****打印单链表******/
{
Node *p;
{
cout << "The LinkList is Empty !" <<endl;
return;
}
while(p!=NULL)
{
cout << p->data << " " ;
p=p->next;
}
}
int main()
{
int length;

cin >> length;
cout << "The new created LinkList as below: " ;
cout << endl;

cout << "Reverse Print LinkList by Recursion: " ;
cout << endl;

cout << "Reverse Print LinkList by stack: " ;