7-2 sdut-C語言實驗-逆序建立鏈表
分數 20
全屏瀏覽
切換布局
作者?馬新娟
單位?山東理工大學
輸入整數個數N,再輸入N個整數,按照這些整數輸入的相反順序建立單鏈表,并依次遍歷輸出單鏈表的數據。
輸入格式:
第一行輸入整數N;;
第二行依次輸入N個整數,逆序建立單鏈表。
輸出格式:
依次輸出單鏈表所存放的數據。
輸入樣例:
10
11 3 5 27 9 12 43 16 84 22
輸出樣例:
22 84 16 43 12 9 27 5 3 11
#include<stdio.h>
#include<stdlib.h>
struct node
{int data;struct node *next;
};
int main()
{int n;struct node *head, *p;head=(struct node*)malloc(sizeof(struct node));//head->next=NULL;scanf("%d",&n);for(int i=0;i<n;i++){p=(struct node*)malloc(sizeof(struct node));scanf("%d",&p->data);p->next=head->next;head->next=p;}p=head->next;while(p){if(p->next==NULL)printf("%d\n",p->data);elseprintf("%d ",p->data);p=p->next;}return 0;
}
?或者
#include<stdio.h>
#include<stdlib.h>
int main()
{int i,j;int *array=NULL;scanf("%d",&i);array=(int*)malloc(i*sizeof(int));for(j=0;j<i;j++){scanf("%d",&array[j]);}for(j=i-1;j>=0;j--){if(j==i-1)printf("%d",array[j]);elseprintf(" %d",array[j]);}return 0;
}