用c语言实现单链表的头插法和尾插法
- 创建结点结构体
——第一部分是数据域----存储数据
——第二部分是指针域----连接结点
例:
typedef struct Listnode{
int data;
struct Listnode* next;
}ListNode;
- 封装创建链表的函数
ListNode* createlist1(){
int i;
ListNode *head,*p;
head=NULL;
printf("请开始输入数据,结束输入输入-1值即可\n");
scanf("%d",&i);
while(i!=-1){
p=(ListNode*)malloc(sizeof(ListNode));
p->data=i;
p->next=head;
head=p;
scanf("%d",&i);
}
return head;
}
ListNode* createlist2(){
int i;
ListNode *head,*p,*r;
head=NULL;
printf("请开始输入数据,输入-1结束\n");
scanf("%d",&i);
while(i!=-1){
r=(ListNode*)malloc(sizeof(ListNode));
r->data=i;
if(head==NULL){
head=r;
}else{
p->next=r;
}
p=r;
scanf("%d",&i);
}
if(p!=NULL) p->next=NULL;
return head;
}
- 主函数
int main(void){
ListNode *p,*q;
int choice;
printf("请选择用头插法创建单链表还是尾插法创建单链表,头插法选1,尾插法选2\n");
scanf("%d",&choice);
getchar();
if(choice==1){
q=CreateList1();
}else if(choice==2){
q=CreateList2();
}else{
printf("输入错误,程序终止\n");
exit(-1);
}
while(q){
printf("%c",q->data);
p=q->next;
free(q);
q=p;
}
printf("\n");
return 0;
}