单向链表4
题目描述:
定义单向链表:输入若干个正整数(输入-1为结束标志),要求按输入数据的逆序并输出。
输入输出示例:括号内为说明
题目输入:
题目输出:
思路分析:
这道题其实目的性很简单,就是要逆序输出,可以直接用递归方式来输出即可,直接看代码把。
代码:
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<iostream>
#include<stack>
using namespace std;
int b;
typedef struct Lemon1//定义数据结构
{
int num;
struct Lemon1* next;//定义结构指针
}Lemon;
Lemon* LemonScanf()
{
Lemon *p,*head,*end;//定义操作指针,头指针,尾指针
head=(Lemon*)malloc(sizeof(Lemon));
end=head;//将头指针赋予尾指针
for(int i=0;;i++)
{
p=(Lemon*)malloc(sizeof(Lemon));//开创空间
cin >> p->num;//输入数字
if(p->num==-1)//当得到数字为-1结束
break;
end->next=p;//将end结构中的结构next指针指向p指针中,
end=p;//在将P数据结构赋于end,相当于end变成了p了。
}
end->next=NULL;//结束创建
return head->next;//这里是返回头指针的下一个指针,如果返回头指针,
//输出的时候会错乱。
}
void LemonPrintf(Lemon* root,int num1)
{
if(root==NULL)
{
return;
}
LemonPrintf(root->next,num1+1);
if(num1==0)//这里是为了满足格式,因为最后一个数字输出的时候后面不能带有空格
printf("%d",root->num);
else
printf("%d ",root->num);
}
int main()
{
Lemon* root;//接受指针
root=LemonScanf();//创建链表
LemonPrintf(root,0);
}