#include<stdio.h>
#include<stdlib.h>
//创建链表结构体
struct test
{
int data;
struct test *next;
};
//打印链表函数
//原理:当链表不为空的时候,依次循环往下遍历,每次遍历的时候打印数据
void shuc(struct test *o)
{
while(o!=NULL)
{
printf("%d ",o->data);
o=o->next;
}
printf("\n");
}
//静态后插入函数
//原理:通过遍历找到要插入的数据位置,然后让新节点指向原链表节点的下一个节点,原链表节点指向新节点
void hcharu(struct test *c,int data,struct test *r)
{
while(c!=NULL)
{
if(c->data==data)
{
r->next=c->next;
c->next=r;
}
c=c->next;
}
}
//静态前插入函数
//原理:通过遍历找到要插入的数据位置,如果该位置是链表头节点,则让新节点指向链表头节点,否则让新节点指向该节点,原该节点前面的节点指向新节点
struct test* qcharu(struct test *c,int data,struct test *r)
{
if(c->data==data)
{
r->next=c;
return r;
}
while(c->next!=NULL)
{
if(c->next->data==data)
{
r->next=c->next;
c->next=r;
return c;
}
c=c->next;
}
printf("插入失败");
return c;
}
//删除节点函数
//很简单,懒得写
struct test* shanchu(struct test *l,int data)
{
struct test* pp=l;
if(pp->data==data)
{
l=l->next;
free(pp);
return l;
}
while(l->next!=NULL)
{
if(l->next->data==data)
{
l->next=l->next->next;
return l;
}
l=l->next;
}
}
//查找节点函数
//很简单,懒得写
int chazhao(struct test *l,int data)
{
int i=0;
while(l!=NULL)
{
i++;
if(l->data==data)
{
printf("找到了:%d,在链表第%d个位置上",data,i);
return 0;
}
l=l->next;
}
}
//改节点函数
//很简单,懒得写
int gai(struct test *l,int data,int newdata)
{
while(l!=NULL)
{
if(l->data==data)
{
l->data=newdata;
return 0;
}
l=l->next;
}
}
//动态头插入法
struct test* dttoucha(struct test* m)
{
while(1)
{
struct test* n=(struct test*)malloc(sizeof(struct test));
printf("请输入要插入的数据");
scanf("%d",&(n->data));
if(m==NULL)
{
m=n;
}
if(n->data==0)
{
return m;
}
else
{
n->next=m;
m=n;
}
}
}
//动态尾插入法
struct test* dtweicha(struct test* m)
{
struct test* a=m;
struct test* b;
while(a!=NULL)
{
b=a;
a=a->next;
}
while(1)
{
struct test* n=(struct test*)malloc(sizeof(struct test));
printf("请输入要插入的数据");
scanf("%d",&(n->data));
b->next=n;
b=b->next;
if(n->data==0)
{
return m;
}
}
}
int main()
{
int i;
struct test *t0=(struct test*)malloc(sizeof(struct test));
struct test *t5=(struct test*)malloc(sizeof(struct test));
struct test t1={1,NULL};
struct test t2={2,NULL};
struct test t3={3,NULL};
struct test t4={4,NULL};
t0->data=0;
t0->next=&t1;
t5->data=100;
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
// 测试样例
// shuc(t0);
// hcharu(t0,2,t5);
// t0=qcharu(t0,1,t5);
// shuc(t0);
// t0=shanchu(t0,0);
// shuc(t0);
// printf("\n");
// printf("%d %d %d",t0->data,t0->next->data,t0->next->next->data);
// chazhao(t0,4);
shuc(t0);
// gai(t0,2,5);
// t0=dttoucha(t0);
t0=dtweicha(t0);
shuc(t0);
return 0;
}
链表入门
最新推荐文章于 2023-10-28 17:28:48 发布