单链表的操作
来源:互联网 发布:mac云盘下载速度慢 编辑:程序博客网 时间:2024/06/11 07:27
#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#)
- 单链表的操作
- 单链表的各种操作
- 单链表的操作实现
- 单链表的 操作
- 单链表的基本操作
- 单链表的一些操作
- 单链表的操作
- 关于单链表的操作
- 单链表的各种操作
- 单链表的常用操作
- 单链表的一些操作
- 单链表的一些操作
- 单链表的操作
- 解决Memsql中group_concat内部排序问题
- 人生感悟(换位思考)
- pl/sql基础知识学习笔记(一)
- 设置xcode7模拟器键盘显示中文步骤
- AsyncTask详解及源码分析
- 单链表的操作
- 浙大PAT甲级 1038
- mysql密码忘记了怎么办,重置密码步骤
- C语言再学习 -- 标识符
- Mapped Statements collection does not contain value for
- hdu 5834 Magic boy Bi Luo with his excited tree 树形dp
- 数据结构:删除单向链表中的某一个节点
- NBUT 1647 又一道简单题
- 图的邻接表存储