当前位置:文档之家› 线性表的插入和删除

线性表的插入和删除

实验一线性表的基本操作
一、实验目的
掌握线性表的基本操作,插入、删除、查找,以及线性表合并等运算在顺序存储结构上的运算。

二、实验要求
1、认真阅读和掌握本实验的程序。

2、上机运行本程序。

3、保存和打印出程序的运行结果,并结合程序进行分析。

4、按照你对线性表的操作需要,重新改写主程序并运行,打印出文件清单
和运行结果
三、实验内容
线性表基本操作的实现。

算法描述:对每一个算法,要写出算法的中文描述。

本实验中要求写出在第i 个结点前插入数据为x的结点、删除指定结点、创建一个线性表、打印线性表的算法描述。

四、程序清单
1、sqlist.h文件清单:
#include "stdio.h"
#include "malloc.h"
#define null 0
#define maxsize 1024
typedef char datatype;
typedef struct
{
datatype data[maxsize];
int last;
}sequenlist;
/*在第i个结点前插入元素x(note:元素从0始计数)*/
int insert(sequenlist *L, datatype x,int i)
{
int j;
if (L->last==maxsize-1)/*如果原线性表已经满了*/
{
printf("overflow");
return 0;
}
else if ((i<0)||(i>L->last)) /*如果输入的i值超出范围*/
{
printf("error,please input the right 'i'");
return 0;
}
else
{
for(j=L->last; j>=i; j--) /*从第i个元素起,每个元素后移一位*/
L->data[j+1]=L->data[j];
L->data[i]=x;
L->last=L->last+1;
}
return(1);
}
/*删除第i个结点,note:元素从0始计数*/
int dellist(sequenlist *L,int i)
{
if ((i<0)||(i>L->last)) /*如果输入的i值超出范围*/
{
printf ("error,please input the right i");
return 0;
}
else
{
for(;i<L->last; i++) /*从第i+1个元素起,每个元素前移一位*/ L->data[i]=L->data[i+1];
L->last=L->last-1;
return(1);
}
}
/*创建顺序表*/
void creatlist(sequenlist *L)
{
int n , i;
char tmp;
printf("请输入数据的个数:\n");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("data[%d]=", i);
fflush(stdin); /*清除掉键盘缓冲区*/
scanf ("%c", &tmp);
L->data[i] = tmp;
}
L->last=n-1;
printf("\n");
}
/*打印顺序表*/
void printout(sequenlist *L)
{
int i;
for(i=0; i<=L->last; i++)
{
printf("data[%d]=", i);
printf("%c\n", L->data[i]);
}
}
2、main.c文件清单
#include "sqlist.h"
main()
{
sequenlist *L;
char cmd, x;
int i;
L=(sequenlist *)malloc(sizeof(sequenlist)); /*指针在使用前一定要初始化*/ creatlist(L); /*创建线性表*/
do
{
printf("i,I......插入\n");
printf("d,D......删除\n");
printf("q,Q......退出\n");
do
{
fflush(stdin); /*清除掉键盘缓冲区*/
scanf("%c",&cmd);
}
while((cmd!='d')&&(cmd!='D')&&(cmd!='q')
&&(cmd!='Q')&&(cmd!='i')&&(cmd!='I'));
switch (cmd)
{
case 'i':
case 'I':
printf("请输入你要插入的数据:");
fflush(stdin); /*清除掉键盘缓冲区*/
scanf("%c",&x);
printf("请输入你要插入的位置:");
scanf("%d",&i);
insert(L, x, i);
printout(L);
break;
case 'd':
case 'D':
printf("请输入你要删除元素的位置:");
fflush(stdin); /*清除掉键盘缓冲区*/
scanf("%d",&i);
dellist(L, i);
printout(L);
break;
}
}while ((cmd!='q')&&( cmd!='Q'));
}。

相关主题