还不太了解单链表如何创建的同学请点击链接
https://blog.csdn.net/tongjingqi_/article/details/105831323
想了解单链表的排序和查找的同学请点击
https://blog.csdn.net/tongjingqi_/article/details/105927156
本篇实现单链表的插入删除修改
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* add_head(struct node* head,int x)//实现在开始结点前增加一个新结点
{
struct node *p=(struct node *)malloc(sizeof(struct node));
p->next=head;
p->data=x;
head=p;
return head;
}
void add_tail(struct node* head,int x)//实现在最后一个结点增加新结点
{
struct node *p=(struct node *)malloc(sizeof(struct node));
struct node *q=(struct node *)malloc(sizeof(struct node));
q->next=NULL;
q->data=x;
for(p=head;p->next!=NULL;p=p->next);//找到最后一个结点
p->next=q;//把最后一个结点指向新增的结点
};
struct node* insert(struct node* head,int x)//把x插在第一个大于x的数之前
{
struct node *p=(struct node *)malloc(sizeof(struct node));
struct node *q=(struct node *)malloc(sizeof(struct node));
struct node *r=(struct node *)malloc(sizeof(struct node));
for(p=head,q=head;p->data<x&&p->next!=NULL;p=p->next)q=p;//找到插入点的前后两个指针q和p,注意赋值顺序
if(p==head)head=add_head(head,x);//头部插
else if(p->next==NULL)add_tail(head,x);//尾部插
else{中间插
r->data=x;
r->next=p;
q->next=r;
}
return head;
}
struct node* Delete(struct node* head,int x)//删除值为x的结点
{
struct node *p=(struct node *)malloc(sizeof(struct node));
struct node *q=(struct node *)malloc(sizeof(struct node));
for(p=head,q=head;p->data!=x&&p->next!=NULL;q=p,p=p->next);//先找到x的位置
if(p==head)
{
head=p->next;//x是第一个数据的情况
free(p);
}
else {
q->next=p->next;//直接把被删结点的前一个结点的next指向被删结点后一个结点
free(p);
}
return head;
};
void Delete_alvl(struct node* head)//整条链表的删除
{
struct node *p=(struct node *)malloc(sizeof(struct node));
struct node *q=(struct node *)malloc(sizeof(struct node));
for(p=head,q=head;q!=NULL;q=q->next,free(p),p=q);
}
struct node* change(struct node* head,int x,int y)
{
struct node *p=(struct node *)malloc(sizeof(struct node));
for(p=head;p!=NULL;p=p->next)
{
if(p->data==x){
p->data=y;
return p;
}
}
}
int main()
{
int i,n;
scanf("%d",&n);
struct node *p,*q,*head=NULL;
for(i=0;i<n;i++)//创建链表
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&(p->data));
if(head==NULL)head=p;
else q->next=p;
q=p;
}
p->next=NULL;
for(p=head;p!=NULL;p=p->next)//遍历链表并输出
{
printf("%d ",p->data);
}
printf("\n");
head=add_head(head,100);//
add_tail(head,77);
head=insert(head,-1);
head=insert(head,101);
head=insert(head,4);
for(p=head;p!=NULL;p=p->next)
{
printf("%d ",p->data);
}
printf("\n");
head=Delete(head,4);
for(p=head;p!=NULL;p=p->next)
{
printf("%d ",p->data);
}
printf("#");
p=change(head,1,111111);
if(p!=NULL)printf("%d",*p);
Delete_all(head);
return 0;
}