这道题的算法思想是从尾部插入元素来建立单链表。
#include <stdio.h>
#include <malloc.h>
struct node{/*单链表的定义*/
int data;
struct node* next;
};
struct node* Creatlist(int n){/*从尾部插入,创建单链表*/
struct node* head,*tail,*p;/*需要定义一个尾指针*/
int i,d;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for (i=1;i<=n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&d);
p->data=d;
p->next=NULL;
tail->next=p;
tail=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,n;
struct node* head;
scanf("%d",&n);
head=Creatlist(n);
Putlist(head);
return 0;
}