線性表增刪改查(新版)

#include <iostream>
using namespace std;
#define maxSize 100
#define error -1
typedef struct
{
    int data[maxSize];
    int length=0;
} Sqlist;

void ListInit(Sqlist &L)// init a new List
{
    cout<<"Input data of L: "<<endl;
    for(int i=0;i<10;i++)
    {

        L.data[i]=i;
        L.length++;
    }

    /*int x,i=0;
    while(cin>>x)
    {
        L.data[i++]=x;
        L.length++;
    }*/
    cout<<"over!"<<endl;
}

void insertElem(Sqlist &L,int position,int x)//insert x into L[position]
{
    for(int i=L.length-1; i>=position; i--)
    {
        L.data[i+1]=L.data[i];
    }
    L.data[position]=x;
    L.length++;
}

void deleteElemByPosition(Sqlist &L,int position)//delete element by position
{
    for(int i=position; i<L.length; i++)
    {
        L.data[i]=L.data[i+1];
    }
    L.length-=1;
}

void deleteElemsByData(Sqlist &L,int x)//delete elements by data
{
    for(int i=0; i<L.length; i++)
    {
        if(L.data[i]==x)
        {
            deleteElemByPosition(L,i);
        }
    }
}

void updateElemByPosition(Sqlist &L,int position,int x)//update elemenet which located in position with x
{
    L.data[position]=x;
}

void updateElemByData(Sqlist &L,int oldvalue,int newvalue)//update elements which equals old with new
{
    for(int i=0;i<L.length;i++)
    {
        if(L.data[i]==oldvalue)
        {
            updateElemByPosition(L,i,newvalue);
        }
    }
}

int findElemByPosition(Sqlist L,int position)//find element located in position
{
    return L.data[position];
}
int findElemByData(Sqlist L,int x)//return first Element which equals x.
{
    int i=0;
    for(i=0; i<L.length; i++)
    {
        if(x==L.data[i])
        {
            return i;
        }
    }
    return error;
}
int findElemSum(Sqlist L,int x)//return the sum of Elements which equal x;
{
    int sum=0;
    for(int i=0; i<L.length; i++)
    {
        if(x==L.data[i])
        {
           sum++;
        }
    }
    return sum;
}

void printState(Sqlist L)
{
    cout<<"L's length is: "<<L.length<<endl;
    cout<<"L's data is: ";
    for(int i=0;i<L.length;i++)
    {
        cout<<L.data[i]<<" ";
    }
    cout<<endl;
}

int main()
{
    Sqlist L;

    ListInit(L);
    printState(L);
    cout<<endl;

    insertElem(L,5,-1);
    printState(L);
    cout<<endl;

    deleteElemByPosition(L,5);
    printState(L);
    cout<<endl;

    deleteElemsByData(L,1);
    printState(L);
    cout<<endl;

    updateElemByPosition(L,5,-2);
    updateElemByPosition(L,6,-2);
    printState(L);
    cout<<endl;

    updateElemByData(L,-2,-3);
    printState(L);
    cout<<endl;

    cout<<findElemByData(L,-3)<<endl;
    cout<<findElemByPosition(L,2)<<endl;
    cout<<findElemSum(L,-3)<<endl;
    return 0;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章