纯自己写的,就是想试一下自己对指针、链表内容的理解程度,没有经过大量测试,只自己小小的测试了一下。
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct NODE
{
int value;
struct NODE *next;
};
struct NODE *creat();
void show(struct NODE *first);
bool insert(struct NODE * first,int postion,int value);
bool delete(struct NODE * first,int postion);
bool updata(struct NODE * first,int postion,int value);
int select(struct NODE * first,int value);
int main()
{
struct NODE *first;
first=creat();
//delete(first,2);
//insert(first,2,100);
//updata(first,2,111);
printf("%d\n",select(first,2));
show(first);
}
/*******创建链表,-1表示结束*******/
struct NODE *creat()
{
int value;
struct NODE *p;
struct NODE *q;
struct NODE *first=NULL;
while(1)
{
p = (struct NODE *)malloc(sizeof(struct NODE));
if(p==NULL)
{
printf("分配失败");
return NULL;
}
if(first==NULL)
{
q=p;
first=q;
}
else
{
q->next=p;
q=p;
}
scanf("%d",&value);
if(value == -1)
{
q->next=NULL;
break;
}
p->value=value;
}
return first;
}
/*******查找数值为value的节点,返回是第几个节点*******/
int select(struct NODE * first,int value)
{
struct NODE *p;
p=first;
int i=1;
while(p->value!=value)
{
if(p==NULL)
{
printf("节点不存在");
return 0;
}
i++;
p=p->next;
}
return i;
}
/*******查找数值为value的节点,返回是第几个节点*******/
bool insert(struct NODE * first,int postion,int value)
{
struct NODE *p;
p=first;
for(int i=1;i<postion;i++)
{
if(p==NULL)
{
printf("插入无效");
return false;
}
p=p->next;
}
struct NODE *e = (struct NODE *)malloc(sizeof(struct NODE));
e->value=value;
e->next=p->next;
p->next=e;
return true;
}
/*******删除某个节点*******/
bool delete(struct NODE * first,int postion)
{
struct NODE *p;
struct NODE *q;
p=first;
for(int i=1;i<postion;i++)
{
if(p==NULL)
{
printf("删除无效");
return false;
}
q=p;
p=p->next;
}
if(p->next==NULL)
{
q->next=NULL;
}
else
{
q->next=p->next;
}
free(p);
return true;
}
/*******更新位置为postion的节点数据为value*******/
bool updata(struct NODE * first,int postion,int value)
{
struct NODE *p;
p=first;
for(int i=1;i<postion;i++)
{
if(p==NULL)
{
printf("更新无效");
return false;
}
p=p->next;
}
p->value=value;
return true;
}
/*******遍历链表*******/
void show(struct NODE *first)
{
int value;
struct NODE *p;
p=first;
while(p->next!=NULL)
{
printf("%d",p->value);
p=p->next;
}
}