顺序建表:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int main(){
int n,i;
struct node *p,*head,*tail;
scanf("%d",&n);
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=0;i<n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
p=head->next;
while(p){
if(p->next!=NULL){
printf("%d ",p->data);
}
else
printf("%d\n",p->data);
p=p->next;
}
return 0;
}
逆序建表:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int main(){
int n,i;
struct node *p,*head;
scanf("%d",&n);
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
for(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 ",p->data);
}
else
printf("%d\n",p->data);
p=p->next;
}
return 0;
}