学习心得:C语言中,要掌握链表,除了基本的知识外,还要有对指针的理解在这里特别是指向结构体的指针,由于知识比较抽象,必要时可通过画图方便理解。
运行结果
源代码(每个函数都有说明参数和功能)
#include <stdio.h>
#include <stdlib.h>
struct list{
struct list *next; //指针域
int number;//数据域
};
struct list *head;
//功能:创建头节点
//返回值:头结点指针
struct list * setList();
//功能:头插法
//参数:头节点指针 head
void in_head(struct list *head);
//功能:尾插法
//参数:头节点指针 head
void in_tail(struct list *head);
//功能:输出链表成员
//参数:头节点指针
void out(struct list *head);
//功能:指定位置插入元素
//参数:头节点
void insert(struct list *head);
//功能:删除指定位置节点
//参数:头节点指针
void delete_list(struct list *head);
//功能:回收内存
//参数:头节点指针
void destory(struct list *head);
int main(){
struct list *head;
head=setList();
//in_head(head);
in_tail(head);
out(head);
// delete_list(head);
insert(head);
out(head);
destory(head);
return 0;
}
struct list * setList(){
struct list *head;
head=(struct list *)malloc(sizeof(struct list ));
head->next=NULL;
printf("头节点建立成功\n");
return head;
}
void in_head(struct list *head){
printf("头插法:输入链表成员,以-1结束\n");
int i;struct list *p;
scanf("%d",&i);
while(i!=-1){
p=(struct list *)malloc(sizeof(struct list));
p->next=head->next;
head->next=p;
p->number=i;
scanf("%d",&i);
}
printf("输入成功\n");
}
void in_tail(struct list *head){
printf("尾插法:输入链表成员,以-1结束\n");
int i;struct list *p;
scanf("%d",&i);
while(i!=-1){
p=(struct list *)malloc(sizeof(struct list));
p->number=i;
scanf("%d",&i);
p->next=head->next;
head->next=p;
head=p;
}
}
void out(struct list *head){
printf("顺序输出:");
head=head->next;
do{
printf("%d.",head->number);
head=head->next;
}while(head!=NULL);
printf("\n");
}
void insert(struct list *head){
int x;int i;
printf("输入插入位置:");
scanf("%d",&i);
printf("输入插入元素:");
scanf("%d",&x);
struct list *p=NULL;
p=(struct list *)malloc(sizeof(struct list));//申请备胎空间
p->number=x;//备胎赋值
for(;i>1;i--){
head=head->next;
}
//插入
p->next=head->next;
head->next=p;
}
void delete_list(struct list *head){
printf("输入所要删除元素的位置");
struct list *p;
int i=0;
scanf("%d",&i);
for(;i>1;i--)
head=head->next;
p=head;
p=p->next;
head->next=p->next;
}
void destory(struct list *head){
struct list *p;
do{
p=head->next;
free(head);
head=p;
}while(head->next!=NULL);
printf("\n销毁成功\n");
}