单链表的创建、打印完整程序

#include
#include
#include "time.h"
typedef struct Node{
int data;
struct Node *next;
} Node,*LinkList;


LinkList createList(int n){
LinkList head;LinkList p;
int i;
srand(time(0)); //启动随机数 
head=(LinkList)malloc(sizeof(Node));//申请一个空间建立头节点 
if(!head) printf("memory malloc error!\n");//申请空间失败
head->data=1;
head->next=NULL;
for(i=1;i<=n;i++){

p=(LinkList)malloc(sizeof(Node));
if(!p) printf("memory malloc error!\n");
p->data=rand()%10+1;
p->next=head->next;
head->next=p;

}
return head;

}


LinkList createList_2(int n){
LinkList l,p,q;
int i;
srand(time(0));
l=(LinkList)malloc(sizeof(Node));
if(!l) printf("memory error!\n");
p=l;
l->data=1;
for(i=1;i q=(LinkList)malloc(sizeof(Node));
if(!q) printf("memory error!\n");
q->data=rand()%10+1;
p->next=q;
p=q;
}
p->next=NULL;
return l;

}


void output(LinkList L){
LinkList p;
int i;
p=L;
do{
printf("%d\t",p->data);
i++;
if(i%5==0){
printf("\n");
}
p=p->next;
}while(p->next!=NULL);

}


int main(){
LinkList head;
int n,c;
printf("这是一个创建链表的程序:\n ");
printf("请选择创建的方式:\n1.头插法\n2.尾插法\n"); 
scanf("%d",&c);
switch(c){
case 1:
printf("输入链表的长度:\n");
scanf("%d",&n);
head=createList(n); 
break;
case 2:
printf("输入链表的长度:\n");
scanf("%d",&n);
head=createList_2(n); 
break;
}
output(head);
system("PAUSE");
return 0;
}

你可能感兴趣的:(数据结构)