这道题的算法思想是从头部插入的方法建立链表。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct node{/*链表的定义*/
int data;
struct node* next;
};
struct node* Creatlist(int n){/*创建链表,从头部插入*/
struct node* head,*p;/*定义结构体变量*/
int i,d;
head=(struct node*)malloc(sizeof(struct node));/*为头指针申请内存空间*/
head->next=NULL;
for (i=1;i<=n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&d);
p->data=d;
p->next=head->next;
head->next=p;
}
return head;
};
void Putlist(struct node* head){/*输出函数*/
struct node* p;
p=head->next;
while (p){
if (p==head->next)
printf("%d",p->data);
else
printf(" %d",p->data);
p=p->next;/*指向下一个节点*/
}
}
int main(){
int i,j,n;
struct node* head;
scanf("%d",&n);
head=Creatlist(n);
Putlist(head);
return 0;
}