主要内容:顺序表插入、删除
特点:存储结构和逻辑结构顺序一样
最大优点:可以方便的随机存取表中任一个结点
缺点:
a、插入或删除操作,除表尾的位置外,其它位置必须移动大量的结点,平均要移动约一半的结点,平均时间复杂度为O(n),效率较低
b、顺序表所占空间必须是连续的,结点数并不固定,只能预先分配空间(静态分配)。难以确定合适的存储空间
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1024
typedef int datatype;
typedef struct
{
datatype data[MAXSIZE];
int last; // subscript of linear list's last node,i.e. length is n = last + 1
}sequenlist;
/* linear list insert operate */
int Insert(sequenlist* L, datatype x, int i)
{
int j;
if (L->last >= MAXSIZE - 1)
{
printf("space overflow!\n");
return 0;
}
else if (i < 1 || (i > L->last + 2))
{
printf("insert in a invalide position!\n");
return 0;
}
else
{
for (j = L->last; j >= i-1; j--)
{
L->data[j+1] = L->data[j]; // give space for insert new data
}
L->data[i-1] = x;
L->last = L->last+1;
}
return 1;
}
/* linear list delete operate */
int Delete(sequenlist* L, int i)
{
int j;
if (i < 1 || (i > L->last + 1))
{
printf("delete position is invalide!\n");
return 0;
}
else
{
for (j = i; j <= L->last; j++)
{
L->data[j-1] = L->data[j];
}
L->last = L->last-1;
}
return 1;
}
int main()
{
sequenlist *L;
int i, ch, n;
while(1) // shouw the menu
{
printf("\n*****Please select:");
printf("\n(1) input sequenlist");
printf("\n(2) insert sequenlist");
printf("\n(3) delete sequenlist");
printf("\n*****End*************");
ch = getch(); // get keyboard input
switch(ch)
{
case '1':
printf("\nPlease input your sequenlist's number n = ");
scanf("%d", &n);
L = (sequenlist*)malloc(sizeof(sequenlist));
for (i = 0; i < n; i++)
{
printf("\n Please input %dth interger:", i+1);
scanf("%d", &L->data[i]);
}
L->last = n-1;
printf("your input sequenlist is:\n");
for (i = 0; i<=L->last; i++)
{
printf("%d\n", L->data[i]);
}
break;
case '2':
printf("\n Please input the value to insert:");
scanf("%d", &n);
printf("\nPlease input the position to insert");
scanf("%d", &i);
printf("\n");
if (Insert(L, n, i))
{
printf("the insert result is:\n");
for (i = 0; i <= L->last; i++)
{
printf("%d", L->data[i]) ;
printf("\n");
}
}
break;
case '3':
printf("\n Please input the delete data's position:");
scanf("%d", &i);
printf("\n");
if (Delete(L, i))
{
printf("the delete result is:\n");
for (i = 0; i<=L->last; i++)
{
printf("%d\n", L->data[i]);
}
}
break;
case '4':
return;
default:
return;
}
}
return 0;
}
输出结果: