您的位置:首页 > 理论基础 > 数据结构算法

c语言数据结构分析2之 链表插入删除

2011-08-14 18:22 405 查看
#include <stdlib.h>
#include <stdio.h>
struct test{
int value;
struct test *next;
};
struct test* create(){ //创建create 函数,返回 struct test* 结构指针 返回的是头部指针
test *head,*tail,*p;
head=tail=NULL;
//head 是保存头部指针,p是当前指针,tail是临时替换的指针,是用来过度的
int i;

for(int j=0;j<4;j++)
{
scanf("%d",&i);
//(数据类型)malloc(sizeof(数据类型)) 动态分配内存,一定要记得用free() 消毁
p=(struct test*)malloc(sizeof(struct test)); //创建结构并开屁空间
p->value=i;
p->next=NULL;

if(head==NULL)
{
head=tail=p;		//保存头部指针
}
else{
tail=tail->next;	//第二次set tail->next 有值了 相当于移动两个变量 的指针
}
tail->next=p;			//当前指针追加在未尾;
}

return head;
};

struct test* insert(struct test* ar,int a,int b)	//添加记录函数
{
// a 是查找的元素,b是要插入的元素 ar 是处理的结构
struct test *p,*q,*s;
s=(struct test*)malloc(sizeof(struct test));
s->value=b;

if(ar==NULL)	//空表时直接返回
{
ar=s;
s->next=NULL;
}

if(ar->value==a)//查找替换的元素是头部的话,直接替换指针
{
s->next=ar;
ar=s;
}else{			//否则遍历查找
p=ar;
while(p->value!=a && p->next!=NULL)	//当找到 a 值的话,while就结束了
{
q=p;	//保存 最后一次循环的p
p=p->next;
}
if(p->value==a)	//循环后的指针
{
q->next=s;  //p 已经是保存下一次p的指针了 所以p 的上一次指针是 q
s->next=p;

}else		//否则就追加在后面
{
p->next=s;
s->next=NULL;
}
}

return ar;
}
struct test* del(struct test* ar,int n)  //删除记录函数
{
struct test *q,*p;
if(ar==NULL)
printf("the table is null\n");
else if(ar->value==n)
{
ar=ar->next;
}else
{
p=ar;
while(p->next!=NULL && p->value!=n)
{
q=p;
p=p->next;
}
if(p->value!=n)
printf("no the num\n");
else
{
q->next=p->next;
free(p);
}
}

return ar;
}

void showDate(struct test* p)  //显示记录函数
{
while (p)
{
printf("%d\n",p->value);
p=p->next;
}
}
int main(int argc, char* argv[])
{

struct test *p,*head;
int a,b,d;
head=NULL;
p=create();
head=p;
showDate(p);

printf("num\n");	//插入操作
scanf("%d",&a);
printf("insert num\n");
scanf("%d",&b);

p=insert(head,a,b);
head=p;//再次保存修改后的数据
printf("new p\n");
showDate(p);

printf("del num\n");	//删除操作
scanf("%d",&d);
p=del(head,d);
showDate(p);

return 0;
}
  


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐