重新学习数据结构,跟着视频教程自己码代码。
把一些要点和心得写在这里,以备自己以后查看。
头文件
#ifndef SQLIST_H_
#define SQLIST_H_
#define MAXSIZE 20
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int length;
}Sqlist;
void InitList(Sqlist *L);
bool IsEmpty(Sqlist *L);
void ListInsert(Sqlist *L, int i, ElemType e);
void ListDelete(Sqlist *L, int i);
void ListPrint(Sqlist *L);
void ListClear(Sqlist *L);
ElemType Get(Sqlist *L, int i);
int Locate(Sqlist *L, ElemType e);
bool IsFind(Sqlist *L, ElemType e);
void ListSort(Sqlist *L);
#endif
执行文件里面是相关函数
#include "sqlist.h"
#include <iostream>
using namespace std;
void InitList(Sqlist *L)
{
for(int k = 0; k<MAXSIZE; k++)
L->data[k] = 0;
L->length = 0;
}
bool IsEmpty(Sqlist *L)
{
return (L->length!=0);
}
void ListInsert(Sqlist *L, int i, ElemType e)
{
int k;
if( L ->length == MAXSIZE ) { cout<<"error"<<endl; return; }
if( i<1 || i>L->length+1 ) { cout<<"error"<<endl; return; }
if( i<=L->length )
{
for( k=L->length-1; k>=i-1; k-- )
L->data[k+1] = L->data[k];
}
L->data[i-1] = e;
L->length++;
}
void ListDelete(Sqlist *L, int i)
{
if( L->length == 0 ) { cout<<"error"<<endl; return; }
if( i<1 || i>L->length ) { cout<<"error"<<endl; return; }
for( int k=i-1; k<L->length-1; k++)
L->data[k] = L->data[k+1];
L->length--;
}
void ListPrint(Sqlist *L)
{
for( int i=0; i<L->length; i++ )
cout << L->data[i] << endl;
}
void ListClear(Sqlist *L)
{
for(int k=0; k<L->length; k++)
L->data[k] = 0;
L->length = 0;
}
ElemType Get(Sqlist *L, int i)
{
if(i<1 || i>L->length) return -1;
return L->data[i-1];
}
int Locate(Sqlist *L, ElemType e)
{
for(int k = 0; k<L->length; k++)
{
if(L->data[k]==e) return k+1;
}
return -1;
}
bool IsFind(Sqlist *L, ElemType e)
{
for(int k = 0; k<L->length; k++)
{
if(L->data[k]==e) return true;
}
return false;
}
void ListSort(Sqlist *L)
{
int i, j;
for(i=0; i<L->length; i++)
{
for(j=i+1; j<L->length; j++)
{
if(L->data[i]>L->data[j])
{
ElemType temp = L->data[j];
L->data[j] = L->data[i];
L->data[i] = temp;
}
}
}
}