题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值
考察 单链表操作、栈、递归等概念。
理解:要实现单链表的输出,那么就需要遍历。遍历的顺序是从头到尾,而节点输出的顺序是从尾到头。因此,先遍历到的节点后输出,这是一个典型的 “后进先出”。
要实现这样的输出,可以使用栈,或,递归。
通过这道题,让我对 “递归在本质上就是一个栈结构” 理解的更加深刻。
代码如下:
/************************************************************************/
/** 题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值 */
/** 时间:2015.7.24 作者:jwt */
/************************************************************************/
#include <iostream>
#include <stack>
using namespace std;
typedef struct node{
int value;
struct node *next;
}Listnode;
/**创建一个单链表,n:表示节点数*/
Listnode * Create_List(int n)
{
int i = 0, elem;
Listnode *head, *temp, *curr;
head = new Listnode;
head->next = NULL;
head->value = n; /**头结点保存数据节点个数*/
curr = head;
while(i < n) /*尾插法,新节点都放在最后*/
{
cout << "please input an elem: " << endl;
cin >> elem;
temp = new Listnode;
temp->value = elem;
temp->next = NULL;
curr->next = temp;
curr = temp;
i++;
}
return head;
}
/**栈实现反向输出单链表*/
void Print_List_Reverse_with_stack(Listnode *head)
{
Listnode *p;
stack<int> temp;
if(NULL == head) /*头结点为空,那么这个链表就不存在*/
return;
else{ /*链表的第一个数据节点是头节点的下一个节点,因此链表为空,就是第一个数据节点为空*/
p = head->next;
if(NULL == p)
{
cout << "该链表为空" << endl;
return;
}
}
do{
temp.push(p->value); /*遍历到的节点数据依次入栈*/
p = p->next;
}while(NULL != p);
while(!temp.empty())
{
cout << temp.top() << ' '; /*输出栈顶元素*/
temp.pop(); /*栈顶元素出栈*/
}
cout << endl;
}
/**递归实现反向输出单链表*/
void Print(Listnode *head) /*递归函数*/
{
if(NULL != head)
{
if(NULL != head->next)
{
Print(head->next);
}
cout << head->value << ' ';
}
}
void Print_List_Reverse_Recursively(Listnode *head) /**加这一步的原因是防止输出头结点*/
{
if(NULL == head)
return;
Listnode *p;
p = head->next;
if(NULL == p)
{
cout << "链表为空" << endl;
return;
}
else{
Print(p);
}
}
int main()
{
Listnode *test;
test = Create_List(5);
Print_List_Reverse_with_stack(test);
Print_List_Reverse_Recursively(test);
return 0;
}
结果如下:
/*点滴积累,我的一小步O(∩_∩)O~*/