链表的基本操作:建立,增加,删除指定位置元素,销毁(C语言)

1 篇文章 0 订阅
1 篇文章 0 订阅

学习心得: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");
} 
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值