插入第 i 个元素,i 的取值为 1<= i <=n+1
删除第 i 个元素,i 的取值为 1<=i<=n
一.插入操作:
1 如果插入位置不合理,掏出异常
2 如果线性表长度大于等于数组长度,抛出异常或动态增加容量
3 从最后一个元素开始向前遍历到第i个元素,分别将他们都向后移动一个位置
4 将要插入的元素填入位置i处;
5 表长加 1
二 删除操作:
1 如果删除位置不合理,抛出异常。
2 取出删除元素
3 从删除元素位置开始遍历到最有一个元素的位置,分别将它们都向前移动一个位置
4 表长减一
#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"
#define MAXSIZE 20
// 存储空间初始分配
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int length ;
}sqlList;
Status InitList(sqlList *L)
{
L->length=0;
return OK;
}
Status GetElem(sqlList L, int i, ElemType *e )
{
if(L.length == 0 || i<1 || i>L.length)
{
return ERROR;
}
*e = L.data[i-1];
return OK;
}
// 在 L 中第 i 个位置 , i 从 1 开始
Status ListInsert(sqlList *L , int i, ElemType e)
{
int k;
if(L->length == MAXSIZE)
return ERROR;
if(i<1 || i>L->length+1)// 0,1,2 可以插到第一个位置,第二个位置,第三个位置,第四个位置
{
return ERROR;
}
if(i<=L->length){// length+1 为表尾(表尾和最后位置不同)
for(k=L->length-1;k>=i-1;k--){ // k 是当前元素的下标 从最后一个下标开始 当前元素的下标>=插入位置的下标
//就把要插入位置的下标对应的元素移走
L->data[k+1]=L->data[k];
}
}
L->data[i-1] = e;
L->length++;
return OK;
}
Status ListDelete(sqlList *L, int i, ElemType *e){
int k;
if(L->length == 0){
return ERROR;
}
if(i<1 || i>L->length){
return ERROR;
}
*e = L->data[i-1];
if(i<L->length){// 如果删除不是最后位置 //length 是最后位置
// for(k=i;k<L->length;k++){ // k 是第 I 个位置
// L->data[k-1]=L->data[k];
// }
for(k=i-1;k<L->length-1;k++){ // k 是第 i 个元素下标的位置 应小于最后一个元素
L->data[k]=L->data[k+1];
}
}
L->length--;
return OK ;
}
int main()
{
sqlList L;
InitList(&L);
ListInsert(&L,1,1);
ListInsert(&L,2,2);
ListInsert(&L,3,3);
ListInsert(&L,4,4);
ListInsert(&L,5,5);
ListInsert(&L,6,6);
int a=0;
ListDelete(&L ,3,&a);
// ListInsert(&L,2,1);
//ListInsert(&L,2,1);
for(int i=0;i<L.length;i++)
printf("%d",L.data[i]);
return 0;
}
总结:
插入平均移动次数:
插入位置 1 2 3 。。。。 n n+1
移动次数 n n-1 n-2 1 0
所以总移动次数为= (n+0)(n+1)/2 = (n+1)n/2
平均移动次数为 =(n+1)n/(2(n+1))=n/2;
删除平均移动次数:
删除位置 1 2 3 。。。。 n
移动次数 n-1 n-2 n-3 0
所以总移动次数为= (n)(n-1+0)/2 = (n-1)n/2
平均移动次数为 =(n-1)n/(2n)=(n-1)/2;
所以插入和删除时,时间复杂度为O(n)
存度数据时,时间复杂度为O(1)
单链表结构和顺序存储的优缺点:
1. 存储方式:顺序存储用一段连续的存储单元
链式存储用一组任意的存储单元存放线性表的元素
2. 时间性能:查找 顺序表 O(1) 单链表 O(n)
插入删除 顺序表 O(n) 单链表 O(1)
3. 空间性能:顺序存储 预分配空间,大小不容易确定
链式存储 有则分配
本文介绍了顺序存储结构中插入和删除操作的实现步骤,包括异常处理、元素移动,并通过实例分析了平均移动次数,得出插入和删除的时间复杂度为O(n),而存储数据的时间复杂度为O(1)。
627

被折叠的 条评论
为什么被折叠?



