Problem A: 逆置線性表(線性表)
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 228 Solved: 118
[Submit][Status][Web Board]
Description
Input
輸入長度n:5
輸入數據:1 2 3 4 5
Output
5 4 3 2 1
Sample Input
5 7 8 9 10 11
Sample Output
11 10 9 8 7
HINT
逆置是數據結構中的題,類似數組中的逆置,即頭尾互換。這裏大家可以先用逆序,即輸出時倒序輸出,以後再用逆置做。
#include <iostream>
#define NULL 0
using namespace std;
struct student//定義結構體
{
int num;
student *next;//結構體中包含一個指向下一節點的指針
};
int n;//定義一個全局變量n;
student *creat(int m)//創建鏈表
{//定義函數,此函數帶回一個指向鏈表頭的指針
student *head,*p1,*p2;
p1=p2=new student;//開闢一個新單元,使p1,p2指向它
cin>>p1->num;//輸入第一個結點
head=NULL;//鏈表爲空的時候,
n=0;
while(p1->num!=NULL)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=new student;
if(n==m)//由m,n確定循環次數
{break;}
else
cin>>p1->num;
}
p2->next=NULL;//將最後一個指針指向“空”
return(head);//返回鏈表第一個結點的地址
}
void print(student *p){//鏈表的遞歸輸出
if(p==NULL)//當p指向“空”時,結束,不返回任何值
return ;
print(p->next);//否則的話指針後移,指向下一個結點
cout<<p->num<<" ";//輸出
}
int main()
{
int m;
cin>>m;
student *head;
student *creat(int);
void print(student *);
head=creat(m);
print(head);
return 0;
}