链表操作C语言版
来源:互联网 发布:wan微型端口 编辑:程序博客网 时间:2024/05/22 14:02
在数据结构中,链表是经常会用到的一种基本的数据结构。
用C语言写了一个链表:
#include <stdio.h>#include <stdlib.h>typedef int T;struct node{T data;struct node* next;};typedef struct node Node;#define SIZE sizeof(Node)Node* find(Node* h,T d);//创建一个节点Node* creat_node(T d){Node* p=malloc(SIZE);p->data=d;p->next=NULL;return p;}//创建链表void creat_list(Node** h){T d;Node* p=NULL;Node* pn=NULL;printf("请输入一个数据:\n");scanf("%d",&d);pn=creat_node(d);*h=pn;//节点类型的指针。p=*h;while(1){printf("请输入一个数据:\n");scanf("%d",&d);if(d==0)break;pn=creat_node(d);p->next=pn;p=p->next;//p指向最后一个节点。}}//遍历链表void travel(Node* h){printf("list:");while(h){printf("%5d",h->data);h=h->next;}printf("\n");}Node* getpos(Node *h,int n){int i;if(h==NULL)return NULL;for(i-0;i<n-1;i++){h=h->next;if(h==NULL)break;}return h;}//增int add(Node* h,T d){Node* pn=creat_node(d);Node* p=h;while(p->next){p=p->next;}p->next=pn;}//插入int Insert(Node** h,int n,T d){if(n<1 || *h==NULL) return 0;Node* pn=creat_node(d);if(n==1){pn->next=*h;*h=pn;return 1;}else{Node* pi=getpos(*h,n-1);pn->next=pi->next;pi->next=pn;return 1;}}//找到数据为d的节点并返回其地址,返回NULL表示失败Node* find(Node* h,T d){while(h){if(h->data==d){return h;} h=h->next;}return NULL;}//删除int delete_node(Node** h,int n){if(*h==NULL){printf("没有节点可以删除!\n");return 0;}if((*h)->next==NULL)printf("只有一个头节点,无法删除!\n");Node* pd=NULL;if(n==1){pd=*h;*h=pd->next;return 1;}if(NULL==getpos(*h,n)){printf("找不到该节点!\n");return 0;}Node* pb=getpos(*h,n-1);pd=pb->next;pb->next=pd->next;free(pd);pd==NULL;pb==NULL;return 1;}//删除数据为d的节点int delete_data(Node** h,T d){if(*h==NULL){printf("没有节点可以删除!\n");return 0;}if((*h)->next==NULL) { printf("只有一个头节点,无法删除!\n"); return 0; } //Node* pb=find(*h,d);//删除掉的节点。 Node* pd=NULL; Node* pt=(*h)->next; while(pt) { if((pt)->data==d) pd=pt; (pt)=(pt)->next; } while(pt) { if((pt)->next==pd){ (pt)->next=(pd)->next; break; } }free(pd);pd==NULL;free(pt);pt==NULL;//pb==NULL;return 1;}//改int change(Node* h,T d,int n){Node* pc=getpos(h,n);if(NULL==pc){printf("没有该节点!\n");return 0;}pc->data=d;return 1;}int main(){Node* head = NULL;creat_list(&head);//创建链表add(head,1000);travel(head);//printf("%p\n",head->next);Node* p=find(head,1);printf("%p\n",p);Insert(&head,2,888);travel(head);delete_node(&head,1);travel(head);delete_data(&head,3);11travel(head);return 0;}
实现了链表的增删改查操作。
2 0
- 链表操作C语言版
- 链表的操作(纯C语言版)
- 数据结构 - C语言版 - 双向链表 所有基本操作
- 数据结构C语言版之链表的操作
- 链表的操作(纯C语言版)
- C语言版单向链表
- 双向链表-C语言版
- 双向链表-C语言版
- 单链表的操作C语言版
- 链表的基本操作(C语言版):建立,插入,删除,查找,输出
- 数据结构C语言版线性链表的12个基本操作
- 数据结构C语言版线性链表的12个基本操作
- 数据结构(C语言版)链队列的基本操作
- 线性表的链式存储及相关操作 C语言版
- 数据结构 - C语言版 - 线性表 所有基本操作
- 线性表实验实现基本操作(C语言版)
- 数据结构之对线性表的操作(C语言版)
- 双向循环链表程序(C语言版)
- c++(2)
- Eclipse中project Explorer栏中java类报错不显示红叉怎么回事
- c++ char/int cin获取转换不匹配问题,
- vue2.0 全局组件和局部组件
- CentOS下SVN服务器的安装与配置
- 链表操作C语言版
- Python-下楼问题
- 2016级ACM寒假训练(七)
- Python数据加载、存储与文件格式
- C语言程序设计现代方法---第六章:循环
- 单例模式
- Oracle12C--此专栏的SQL所需要的建表语句(一)
- c++(3)
- 2016--忆