1. 程式人生 > >用C++結構體實現順序表的諸多功能

用C++結構體實現順序表的諸多功能

hnu type 結構體 clu 刪除 ace break 輸入數據 環境

編譯運行環境為visual studio 2017 for community

#include <iostream>

#include<stdlib.h>

#define maxsize 100

#define ok 0

typedef int elemtype;

typedef int status;

using namespace std;

struct slist

{

elemtype *elem = NULL;

int length;

};

void create(slist&q)//順序表的初始化,構造一個空的順序表L

{

q.elem = new int[maxsize];//為順序表分配一個大小為maxsize的數組空間

q.length = 0;

if (q.elem != NULL) //存儲分配成功

cout << "success" << endl;

else//存儲分配失敗

cout << "faild" << endl;

}

status deleteall(slist &q)

{

delete[]q.elem;//釋放分配空間

return ok;

}

void input(slist &q)//輸入數據

{

int a, b;

cout << "需要輸入的數據個數" << endl;

cin >> a;

cout << "輸入數據"<<endl;

for (int i = 0; i < a; i++)

{

cin >> b;

q.elem[i] = b;

q.length++;

}

cout << "數據已輸入" << endl;

}

status searchnumber(slist q, int v)//查找數據

{

cout << "所查元素的值為" << q.elem[v - 1] << endl;

return ok;

}

status searchdata(slist q, int v)//查找序號

{

int i = 0;

for (; i < q.length; i++)

{

if (q.elem[i] == v)

{

cout << "查找數據序號:" << i + 1 << endl;

break;

}

}

return ok;

}

status insert(slist &q, int n, int data)//插入數據

{

if (n < q.length)

{

for (int i = q.length; i > n-1; i--)

{

q.elem[i] = q.elem[i-1];

}

q.elem[n-1] = data;

}

else

{

q.elem[q.length] = data;

}

q.length++;

cout << "插入數據成功" << endl;

return ok;

}

status deleteone(slist& q, int numb2)

{

if (numb2 > q.length)

{

cout << "刪除值不合法" << endl;

}

else

{

int t, i;

for (i = numb2-1; i < q.length-1; i++)

{

q.elem[i] = q.elem[i + 1];

}

q.length--;

cout << "刪除成功" << endl;

}

return ok;

}

void coutfunction(slist q)

{

cout << "順序表數據如下" << endl;

for (int i = 0; i < q.length; i++)

{

cout << q.elem[i] << endl;

}

}

int main()

{

slist q;

cout << "1. 建立順序表\n";

cout << "2. 輸入數據\n";

cout << "3. 查找\n";

cout << "4. 插入\n";

cout << "5. 刪除\n";

cout << "6. 輸出數據\n";

cout << "0. 退出\n\n";

int choose = 9, numb, data, need1, need2, numb1, numb2,numb0, data1;

while (choose != 0)

{

cin >> choose;

switch (choose)

{

case 0:

break;

case 1:

create(q);

break;

case 2:

input(q);

break;

case 3:

cout << "查找序號按 1,查找數值按 2" << endl;

cin >> numb;

if (numb == 1)

{

cin >> numb0;

need1 = searchnumber(q, numb0);

}

else

{

cin >> numb0;

need2 = searchdata(q, numb0);

}

break;

case 4:

cout << "輸入插入的序號和數值" << endl;

cin >> numb1 >> data1;

insert(q, numb1, data1);

break;

case 5:

cout << "輸入刪除的序號" << endl;

cin >> numb2;

deleteone(q, numb2);

break;

case 6:

cout << "當前順序表為:\n";

coutfunction(q);

break;

}

}

return 0;

system("pause");

}

用C++結構體實現順序表的諸多功能