鏈表訓練~單向鏈表4~解題報告

單向鏈表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);
}

成功樣例:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章