链表操作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
原创粉丝点击