1、可以用栈来做。每经过一个结点时,放入栈中。当遍历完链表后,在遍历栈即可。但是要维护一个栈,比较麻烦。
扩展:该题还有两个常见的变体:
2、
2、递归来实现。每访问一个结点,先递归输出它后面的结点,再输出该结点。这样就能实现从尾到头输出链表。
方法2的代码:
//58.从尾到头输出链表。
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
void Create(node *&head)
{
int i;
cin>>i;
node *p1=NULL,*p2=NULL;
while(i!=-1)
{
if(head==NULL)
{
head=new node;
head->data=i;
p1=head;
p1->next=NULL;
}
else
{
p2=new node;
p2->data=i;
p1->next=p2;
p1=p2;
p1->next=NULL;
}
cin>>i;
}
}
void Print( node *&head)
{
if(head==NULL)
return;
else
{
Print(head->next);
cout<<head->data<<endl;
}
}
void main()
{
node *head=NULL;
Create(head);
Print(head);
system("pause");
}
扩展:该题还有两个常见的变体:
1. 从尾到头输出一个字符串;
2. 定义一个函数求字符串的长度,要求该函数体内不能声明任何变量。
1、
<span style="font-size:18px;">void P_str(char *p)
{
if(*p=='\0')
return;
else
{
P_str(++p);
cout<<*(p-1)<<endl;
}
}</span>
2、
<span style="font-size:18px;">//定义一个函数求字符串的长度,要求该函数体内不能声明任何变量。
#include <iostream>
using namespace std;
int len(char *p)
{
if(*p=='\0')
return 0;
else
return 1+len(++p);
}
void main()
{
char p[100];
cin>>p;
cout<<len(p)<<endl;
system("pause");
}</span>