链表的操作c语言,链表操作C语言版

在数据结构中,链表是经常会用到的一种基本的数据结构。

用C语言写了一个链表:

#include

#include

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

{

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);11

travel(head);

return 0;

} 实现了链表的增删改查操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值