一、线性表的顺序删除操作
参考书(《数据结构(C语言)》–严蔚敏等编著,清华大学出版社) 在实现顺序表的删除操作的同时,还要对表进行合法性的判断,具体相关步骤如下: 删除思想:
1、在使用删除函数时判断删除位置的合法性,i<1 || i>length都是不合法的;
2、将第i位置的元素删除;
3、将第i+1之后的元素前移,补齐位置;
4、表长-1;
相关代码:
#include "stdio.h"
#include "stdlib.h"
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status;
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
int listsize;
} SqList;
Status InitList_Sq(SqList &L);
Status InitList_Sq(SqList &L) {
L.elem = (ElemType *) malloc (LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem) exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}
Status ListAdd_Sq(SqList &L,int n);
Status ListAdd_Sq(SqList &L,int n) {
if (L.length+1 >= L.listsize) {
ElemType* newbase = (ElemType*)realloc(L.elem,
(L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase)exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
for(int i=0; i<n; i++) {
L.elem[i] = i+1;
L.length++;
}
return OK;
}
Status ListInsert_Sq(SqList &L, int i, ElemType e);
Status ListInsert_Sq(SqList &L, int i, ElemType e) {
if(i<1 || i>L.length+1) return ERROR;
if(L.length >= L.listsize) {
ElemType *newbase = (ElemType *) realloc (L.elem,
(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize+=LISTINCREMENT;
}
for(int j=L.length-1; j>=i-1; j--)
L.elem[j+1] = L.elem[j];
L.elem[i-1] = e;
L.length++;
return OK;
}
Status ListDelete_Sq(SqList &L, int i, ElemType e);
Status ListDelete_Sq(SqList &L, int i, ElemType e) {
if(i<1 || i>L.length) return ERROR;
ElemType *p=&(L.elem[i-1]);
e = *p;
ElemType *q = L.elem + L.length - 1;
for(p++; p<=q; p++)
*(p - 1) = *p;
L.length--;
return OK;
}
Status DestoryList_Sq(SqList &L);
Status DestoryList_Sq(SqList &L) {
if(L.elem) delete L.elem;
}
Status LocateElem_Sq(SqList L,ElemType e);
Status LocateElem_Sq(SqList L,ElemType e) {
int i;
for(i=0; i<L.length; i++)
if(L.elem[i]==e) return i+1;
return OK;
}
Status GetElem_Sq(SqList L, int i, ElemType &e);
Status GetElem_Sq(SqList L, int i, ElemType &e) {
if(i<1 || i>L.length) return ERROR;
e=L.elem[i-1];
return OK;
}
Status DisplayList_Sq(SqList L);
Status DisplayList_Sq(SqList L) {
if(!L.elem) return ERROR;
for(int i=0; i<L.length; i++) {
if(i<L.length-1) printf("%d,",L.elem[i]);
else printf("%d",L.elem[i]);
}
return OK;
}
int main(void) {
SqList L;
InitList_Sq(L);
int n,i,e;
ListAdd_Sq(L,5);
scanf("%d",&i);
if(ListDelete_Sq(L,i,e))
DisplayList_Sq(L);
else
printf("删除位置非法");
return OK;
}
实现:
|