链表的创建及其增删查改
链表
链表的使用是在结构体和指针的基础上实现的
创建链表的过程需要用到malloc()函数和free()函数
定义结构体
struct Node
{
int data;
struct Node *next;
};
创建函数
struct Node *Creat() //创建函数
{
struct Node *Head,*p1,*p2; //定义头节点及中间变量
int num;
p2=(struct Node *)malloc(sizeof(struct Node)); //开创空间
Head=p2;
scanf("%d",&num);
while(num!=-1) //遍历取值
{
p1=(struct Node *)malloc(sizeof(struct Node)); //开创空间
p1->data=num;
p2->next=p1;
p2=p1;
scanf("%d",&num);
}
p2->next=NULL;
return Head; //返回头节点,下同
}
插入函数
struct Node *enter(struct Node *Head,int inter,int add) //增加函数
{
struct Node* temp=Head;
//遍历到被增加结点的上一个结点
int i;
for (i=1; i<add; i++) {
if(temp->next==NULL)
{
printf("无此节点\n"); //无此节点
return Head;
}
temp=temp->next;
}
struct Node *c;
c=(struct Node *)malloc(sizeof(struct Node));
c->data=inter;
c->next=temp->next;
temp->next=c;
return Head;
}
删除函数
struct Node *delet(struct Node *Head,int add) //删除函数
{
struct Node* temp=Head;
//遍历到被删除结点的上一个结点
int i;
for (i=1; i<add; i++)
{
if(temp->next==NULL)
{
printf("无此节点\n");
return Head;
}
temp=temp->next;
}
struct Node * del=temp->next;//单独设置一个指针指向被删除结点,以防丢失
temp->next=temp->next->next;//删除某个结点的方法就是更改前一个结点的指针域
free(del);//手动释放该结点,防止内存泄漏
return Head;
}
查找函数
found(struct Node *Head,int add) //查找函数
{
struct Node* temp=Head;
int i,n;
for(i=1;i<add;i++)
{
if(temp->next==NULL)
{
printf("无此节点\n");
return -1;
}
temp=temp->next;
}
n=temp->next->data;
return n;
}
修改函数
struct Node *replace(struct Node *Head,int inter,int add) //修改函数
{
struct Node* temp=Head;
int i,n;
for(i=1;i<add;i++)
{
if(temp->next==NULL)
{
printf("无此节点");
return Head;
}
temp=temp->next;
}
temp->next->data=inter;
return Head;
}
输出函数
void print(struct Node *Head)
{
struct Node *p=Head;
while(p->next!=NULL)
{
p=p->next;
printf("%d ",p->data);
}
}
主函数
int main()
{
int n,m,x,k,add,del,rep,fud;
struct Node *Head;
printf("请输入单链表,以'-1'结束:\n");
Head=Creat();
print(Head);
printf("\n请输入在第几节点插入什么元素:\n");
scanf("%d %d",&n,&m);
enter(Head,m,n);
print(Head);
printf("\n请输入删除节点:\n");
scanf("%d",&del);
delet(Head,del);
print(Head);
printf("\n请输入修改节点及修改后的元素:\n");
scanf("%d %d",&rep,&x);
replace(Head,x,rep);
print(Head);
printf("\n请输入查找节点:\n");
scanf("%d",&fud);
k=found(Head,fud);
printf("%d",k);
}
运行代码
请输入单链表,以'-1'结束:
0 1 2 3 4 5 6 7 8 9 -1
0 1 2 3 4 5 6 7 8 9
请输入在第几节点插入什么元素:
1 1
1 0 1 2 3 4 5 6 7 8 9
请输入删除节点:
7
1 0 1 2 3 4 6 7 8 9
请输入修改节点及修改后的元素:
5 6
1 0 1 2 6 4 6 7 8 9
请输入查找节点:
2
0
请输入单链表,以'-1'结束:
0 1 2 3 4 5 6 7 8 9 -1
0 1 2 3 4 5 6 7 8 9
请输入在第几节点插入什么元素:
20 1
无此节点
0 1 2 3 4 5 6 7 8 9
请输入删除节点:
20
无此节点
0 1 2 3 4 5 6 7 8 9
请输入修改节点及修改后的元素:
20 1
无此节点0 1 2 3 4 5 6 7 8 9
请输入查找节点:
20
无此节点
-1
以上即本人代码,如有错误,还请大佬指正。