顺序表实现增删改查的操作
程序员文章站
2022-05-08 09:08:28
...
更多资料请点击:我的目录
本篇仅用于记录自己所学知识及应用,代码仍可优化,仅供参考,如果发现有错误的地方,尽管留言于我,谢谢!
此篇是顺序表实现增删改查的操作,其中:
"增"包括在顺序表尾、顺序表中增加节点
"删"包括在顺序表头、顺序表中、顺序表尾删除单个或多个节点
"改"包括在顺序表头、顺序表中、顺序表尾更改单个或多个节点数值
"查"只是显示整个顺序表所有节点数值
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
//设计顺序表
struct list
{
int buf[SIZE];
int last;
};
//初始化顺序表
struct list *list_init()
{
struct list *mylist = malloc(sizeof(struct list));
mylist->last = -1;
return mylist;
}
//表尾加入新成员
int addtail(int newdata,struct list *mylist)
{
if((mylist->last)>=(SIZE-1))
{
printf("顺序表已满!\n");
return -1;
}
(mylist->last)++; //下标
mylist->buf[mylist->last] = newdata;
}
//顺序表中间插入新成员
int insert(int olddata,int newdata,struct list *mylist)
{
printf("\n====将%d插入到%d后面====\n",newdata,olddata);
int m = 0;
for(int i = 0; i <= mylist->last; i++)
{
if(mylist->buf[i] == olddata)
{
m = 1;
int n = mylist->last;
(mylist->last)++;
for(int j = 0; j < n-i; j++)
{
mylist->buf[mylist->last-j] = mylist->buf[n-j];
}
mylist->buf[i+1] = newdata;
}
}
if(m == 0)
{
printf("原顺序表没有%d这个成员,插入数据失败!\n",olddata);
}
}
//循序表成员删除
int delete(int olddata, struct list *mylist)
{
int m = 0;//标志位
for(int i = 0; i <= mylist->last;i++)
{
if(mylist->buf[i] == olddata)
{
m =1;
for(int j = i; j < mylist->last;j++)
{
mylist->buf[j] = mylist->buf[j+1];
}
(mylist->last)--;
i--;
}
}
printf("\n=====删除成员%d=====\n",olddata);
if(m == 0)
printf("原顺序表没有%d这个成员,删除数据失败!\n",olddata);
}
//循序表成员数值更改
int change(int olddata, int newdata, struct list *mylist)
{
int m = 0;
printf("\n成员%d数值改为%d\n",olddata,newdata);
for(int i = 0; i <= mylist->last; i++)
{
if(mylist->buf[i] == olddata)
{
mylist->buf[i] = newdata;
m = 1;
}
}
if(m == 0)
printf("原顺序表没有%d这个成员,更改数据失败!\n",olddata);
}
//顺序表各成员数据显示
int show(struct list *mylist)
{
printf("顺序表各成员数据:\t");
for(int i = 0; i <= mylist->last; i++)
{
printf("%d\t",mylist->buf[i]);
}
printf("\n");
}
int main(int argc, char **argv)
{
struct list *mylist = list_init();
addtail(1,mylist);
addtail(3,mylist);
addtail(5,mylist);
addtail(6,mylist);
show(mylist);
insert(1, 2,mylist);
show(mylist);
insert(3, 4,mylist);
show(mylist);
insert(6, 7, mylist);
show(mylist);
delete(1, mylist);
show(mylist);
delete(7, mylist);
show(mylist);
delete(4, mylist);
show(mylist);
change(2, 8,mylist);
show(mylist);
change(5, 8,mylist);
show(mylist);
change(6,8, mylist);
show(mylist);
insert(10, 7, mylist);
show(mylist);
delete(10, mylist);
show(mylist);
change(10,8, mylist);
show(mylist);
return 0;
}
运行输出如下: