创建空顺序线性表——C语言
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
struct seqList {
int MAXNUM;
int curNum;
DataType * element;
};
typedef struct seqList * PseqList;
PseqList createNullList_seq(int m) {
if (m == 0) {
return NULL;
}
PseqList List = (PseqList)malloc(sizeof(struct seqList));
List->MAXNUM = m;
List->curNum = 0;
List->element = (DataType*)malloc(sizeof(DataType)*m);
return List;
}
int isFullList_seq(PseqList L) {
if(L->curNum ==L-> MAXNUM){
return 1;
}else{
return 0;
}
}
int insertP_seq(PseqList L, int p, int x) {
if(isFullList_seq(L)==1){
printf("list is full\n");
return 0;
}
if(p<0||p>L->curNum){
printf("position is illegel\n");
return 0;
}
for(int i=L->curNum;i>p;i--){
L->element[i] = L -> element[i-1];
}
L -> element[p] = x;
L -> curNum++;
return 1;
}
int insertPre_seq(PseqList L, int p, int x) {
return insertP_seq(L, p-1, x);
}
int insertPost_seq(PseqList L, int p, int x) {
return insertP_seq(L, p, x);
}
void printList_seq(PseqList L) {
for(int i = 0; i < L->curNum; i++) {
printf("%d ", L->element[i]);
}
printf("\n");
}
int destroyList_seq(PseqList L) {
if(L == NULL) return 0;
int num = L->curNum;
free(L->element);
free(L);
return num;
}
int locate_seq(PseqList L, int x) {
for(int i = 0; i < L->curNum; i++) {
if(L->element[i] == x) {
return i;
}
}
return -1;
}
DataType locatePos_seq(PseqList L, int pos) {
if(pos < 0 || pos >= L->curNum) {
return L->element[0];
}
return L->element[pos];
}
int deletePos_seq(PseqList L, int pos) {
if(pos < 0 || pos >= L->curNum) {
return -1;
}
for(int i = pos; i < L->curNum-1; i++) {
L->element[i] = L->element[i+1];
}
L->curNum--;
return 1;
}
int delete_seq(PseqList L, int x) {
int cnt = 0;
for(int i = 0; i < L->curNum; i++) {
if(L->element[i] == x) {
deletePos_seq(L, i);
i--;
cnt++;
}
}
return cnt;
}
void replace_seq(PseqList L, int x, int y) {
for(int i = 0; i < L->curNum; i++) {
if(L->element[i] == x) {
L->element[i] = y;
}
}
}
void delDuplicate_seq(PseqList L) {
for(int i = 0; i < L->curNum-1; i++) {
for(int j = i+1; j < L->curNum; j++) {
if(L->element[i] == L->element[j]) {
deletePos_seq(L, j);
j--;
}
}
}
}