用c语言编写链表各种操作,用C语言实现链表的各种操作

#include"stdio.h"

#include

typedef struct List_Node{

int info;

struct List_Node *next;

}node;

//链表长度

int Count_Node(node *head)

{

node *p;

int num=0;

if (head ==NULL)

{

return;

}

p=head->next;

while(p!=NULL)

{

num++;

p=p->next;

}

return num;

}

//按值查找

void FindByValue(node *head, int v)

{

node *p;

int i=0, num=0;

if (head == NULL)

{

return;

}

p=head->next;

while(p!=NULL)

{

i++;

if (p->info==v)

{

num++;

printf("%d ",i);

}

p=p->next;

}

printf("找到%d个等于%d的值",num,v);

}

//插入元素

void InsertItem(node *head, int loc, int num)

{

node *p, *pre, *s;

int i=0;

if (loc>Count_Node(head)||loc<0)

{

printf("插入位置错误\n");

return;

}

if (head == NULL)

{

return;

}

pre=head;

p = head->next;

while(i!=loc)

{

i++;

pre = p;

p=p->next;

}

s=(node*)malloc(sizeof(node));

s->info=num;

s->next=p;

pre->next=s;

}

//删除元素

int deleteItem(node *head, int loc)

{

node *p, *pre;

int i=1, num=0;

if (loc>Count_Node(head)||loc<=0)

{

printf("删除位置错误\n");

return;

}

if (head == NULL)

{

return;

}

pre=head;

p = pre->next;

while(i!=loc)

{

i++;

pre = p;

p=p->next;

}

num = p->info;

pre->next = p->next;

p->next = NULL;

free(p);

return num;

}

//清空链表

void FlushLink(node *head)

{

int *p;

if (head == NULL)

{

return;

}

p = head->next;

head->next = NULL;

free(p);

}

//销毁链表

void DestoryLink(node *head)

{

free(head);

}

//按序号查找

int FindByNo(node *head, int loc)

{

node *p;

int i=1;

if (loc>Count_Node(head)||loc<=0)

{

printf("位置错误\n");

return;

}

if (head == NULL)

{

return;

}

p = head->next;

while(i!=loc)

{

i++;

p=p->next;

}

return p->info;

}

//尾插法建立带头结点的单链表

node* Creat_Node()

{

node *head,*pre,*p;

int x;

head=(node*)malloc(sizeof(node));;

head->next=NULL;

pre=head;

printf("输入各结点的值,以0结束:");

while(EOF!=(scanf("%d",&x))&&x!=0)

{

p=(node*)malloc(sizeof(node));

p->info=x;

p->next=pre->next;

pre->next=p;

pre=pre->next;

}

return head;

}

//头插法建立带头结点的单链表

node* Build_Node()

{

node *head,*p;

int x;

head=(node*)malloc(sizeof(node));;

head->next=NULL;

printf("输入各结点的值,以0结束:");

while(EOF!=(scanf("%d",&x))&&x!=0)

{

p=(node*)malloc(sizeof(node));

p->info=x;

p->next=head->next;

head->next=p;

}

return head;

}

//在Y前插入X

void Before_y_Insert_x(node* head,int y,int x)

{

node *pre,*p,*s;

if (head ==NULL)

{

return;

}

pre=head;

p=pre->next;

while(p&&p->info!=y)

{

pre=p;

p=p->next;

}

if(

p==NULL)

{

printf("error!%d不在该链表中\n",y);

}

else

{

s=(node*)malloc(sizeof(node));

s->info=x;

s->next=p;

pre->next=s;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值