資料結構之線性表演算法的構建與應用
//資料結構值順序線性表的實現與應用
//c++程式碼進行實現
//sqlist.h程式碼 //線性表的初始化
#define MAXSIZE 20
//typedef int ElemType;
typedef struct{
int date[MAXSIZE];
int length;
}sqList;
//getlem.h程式碼
#define OK 1
#define ERROR 0
#define FALSE 0
#define TRUE 1
//typedef int Status;
int Getlem(sqList L, int i, int *e) // 獲取第i個位置上的資料返回給變數e
{
if (L.length == 0 || i<1 || i>L.length)
return ERROR;
*e = L.date[i - 1];
return OK;
}
//listinsert.h程式碼
int ListInsert(sqList *L, int i, int e) //插入演算法
{
int k;
if (L->length == MAXSIZE)
return ERROR;
if (i<1||i>L->length+1)
return ERROR;
if (i <= L->length)
{
for (k = L->length; k > i - 1; k--)
L->date[k] = L->date[k-1];
}
L->date[i-1] = e;
L->length++;
return OK;
}
//listdelete.h程式碼
int ListDelete(sqList *L, int i, int *e) // 刪除演算法
{
int k;
if (i > L->length || i < 1)
return ERROR;
if (L->length == 0)
return ERROR;
*e = L->date[i - 1];
if (i < L->length)
{
for (k =i; k < L->length; k++)
L->date[k - 1] = L->date[k];
}
L->length--;
return OK;
}
//主程式
#include<stdlib.h>
#include<sqList.h>
#include<Getlem.h>
#include<ListDelete.h>
#include<ListInsert.h>
#include<iostream>
#include<ctime>
const int Length = 20;
void main()
{
using std::cout;
using std::cin;
using std::endl;
sqList L;
L.length = Length;
int i = 0;
int ch;
int e;
//線性表的賦值
srand(time(NULL));
for (; i < L.length; i++)
{
L.date[i] = rand() % 100 + 1;
}
////線性表的列印輸出
cout << "sqList:";
for ( i = 0; i < Length; i++)
{
cout << L.date[i] <<" ";
}
cout << endl;
//獲取第8位置上的元素的值
ch=Getlem(L, 8, &e);
cout << "getlem ch:" << ch<<endl;
cout << "getlem e:" << e << endl;
//刪除第8 個元素上面的值
ch=ListDelete(&L, 8, &e);
cout << "listdelete ch:" << ch << endl;
cout << "listdelete e:" << e << endl;
for (i = 0; i < L.length; i++)
{
cout << L.date[i] << " ";
}
//在第八個元素位置插入數值233
ch = ListInsert(&L, 8, 233);
cout << "listinsert ch:" << ch << endl;
cout << "listinsert e:" << e << endl;
for (i = 0; i < L.length; i++)
{
cout << L.date[i] << " ";
}
system("pause");
}