数据结构复习(一)顺序表的基本操作

#include<iostream>
#include<cstdio>    // C语言头文件
#include<cstdlib>  // malloc头文件
using namespace std;


typedef struct{
    int* data;
    int length, MaxSize;  // length为当前元素数量,MaxSize为最大元素数量
}SqList;

void InitList(SqList &L){
    L.length = 0;
    L.MaxSize = 10;
    L.data = (int*)malloc(L.MaxSize * sizeof(int));
}

bool ListInsert(SqList &L, int pos, int value){
    if(L.length >= L.MaxSize) return false;
    if(pos < 1 || pos > L.length + 1) return false;
    int i;
    for(i = L.length; i >= pos; i--){
        L.data[i] = L.data[i - 1];
    }
    L.data[i] = value;
    L.length++;
}

void PrintList(SqList &L){
    for(int i = 0; i < L.length; i++){
        cout<<L.data[i]<<" ";
    }
    cout<<endl;
}

void Del_X(SqList &L, int x){
    int k = 0, i;
    for(i = 0; i < L.length; i++){
        if(L.data[i] == x){
            k ++;
        }else{
            L.data[i - k] = L.data[i];
        }
    }
    L.length -= k;
}

int main(){
    SqList L;
    InitList(L);
    int i;
    int orign[10] = {3, 2, 1, 2, 2, 5, 7};
    for(i = 0; i < 7; i++){
        ListInsert(L,1, orign[i]);
    }
    PrintList(L);
    Del_X(L, 2);
    PrintList(L);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/C_Ronaldo_/article/details/82934923