链表是一种重要的数据结构,对链表的相关操作要掌握,这次只是单向动态链表的相关简单操作。
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct note)
int main()
{
struct note
{
int num;
struct note *next;
};
//结点的定义
void search(struct note *head,int n) //查询数据的函数
{
struct note *p;
int i;
p=head;
for(i=0;i<n-1;i++)
{
p=p->next;
}
printf("你所查询的第%d个数据为:%d\n",n,p->num);
}
void change(struct note *head,int n,int date) //查询数据并做修改
{
struct note *p;
int i;
p=head;
for(i=0;i<n-1;i++)
{
p=p->next;
}
p->num=date; //查找到需修改的数据,进行修改
printf("修改后的链表如下:\n"); //输出修改后的链表
do
{
printf("%d ",head->num);
head=head->next;
}while(head!=NULL);
printf("\n");
}
void insert(struct note *head,int n,int date) //对链表进行插入处理
{
struct note *p,*p1,*p2;
int i;
p=head;
for(i=0;i<n-2;i++)
{
p=p->next;
}
p1=p2=(struct note*)malloc(LEN);
p2->next=p->next;
p->next=p1;
p1->num=date;
printf("插入后的链表如下:\n"); //输出插入节点后的链表
do
{
printf("%d ",head->num);
head=head->next;
}while(head!=NULL);
printf("\n");
}
void _delete (struct note *head,int n) // 删除节点的函数
{
struct note *p,*p1;
p=head;
int i;
p1=(struct note*)malloc(LEN);
for(i=1;i<n;i++)
{
p=p->next; //执行n-1次后p指针指向第n个节点
}
p1->next=p->next;// 此时的p->next指向第n+1个节点的地址,将地址赋给p1节点的next
p=head;//初始化*p 使它指向链表头
for(i=1;i<n-1;i++)
{
p=p->next; //同上,此时的p指针指向第n-1个节点
}
p->next=p1->next; //将n+1个节点的地址赋给n-1个节点的指针域,即删除掉了第n个节点,达到目的
printf("删除后的链表如下:\n");
do
{
printf("%d ",head->num);
head=head->next;
}while(head!=NULL);
printf("\n");
}
void add(struct note *head,int n,int date)// 增加一个节点
{
struct note *p,*q;
int i;
q=(struct note*)malloc(LEN);
q->num=date;
p=head;
for(i=1;i<n-1;i++)
{
p=p->next;
} //循环完后p指针指向第n-1个节点
q->next=p->next; //将第n-1个节点的地址域即第n个节点的地址赋给刚刚建立的q节点的地址域
p->next=q; //再将新建的q节点的地址赋给n-1的next,完成链表的链接
printf("增加后的链表如下:\n");
do //输出增加节点后的链表
{
printf("%d ",head->num);
head=head->next;
}while(head!=NULL);
printf("\n");
}
printf("请输入链表数据,0或-1结束输入、\n");
int m,l,a,s,x,g,z,j;
struct note *head,*p1,*p2,*p;
p1=p2=(struct note*)malloc(LEN); //动态链表的建立
scanf("%d",&p1->num);
head=p1;
while(p1->num&&p1->num!=-1)//以0或-1 作为结束链表输入的操作
{
p2->next=p1;
p2=p1;
p1=(struct note*)malloc(LEN);
scanf("%d",&p1->num);
}
p2->next=NULL;
p=head;
do //输出刚刚创建的动态链表
{
printf("%d ",p->num);
p=p->next;
}while(p!=NULL);
printf("\n");
printf("请输入要查询的数据位置:\n");
scanf("%d",&m);
search(head,m);
printf("请输入要修改的数据位置及修改数据:\n");
scanf("%d %d",&x,&g);
change(head,x,g);
printf("请输入要插入的数据位置及插入数据:\n");
scanf("%d %d",&l,&a);
insert(head,l,a);
printf("请输入要要删除的结点位置:\n");
scanf("%d",&s);
_delete(head,s);
printf("请输入要增加的数据位置及增加的数据:\n");
scanf("%d %d",&z,&j);
add(head,z,j);
return 0;
}
程序运行后截图: