浙江大学数据结构陈越老师视频课程
线性表代码整理
- 线性结构头文件
//structList.h
#include <iostream>
//define maxsize of list
#define MAXSIZE 100
//define structure of list
typedef struct LNode *List;
struct LNode{
double Data[MAXSIZE];
int Last;
};
//initialize of list
List MakeEmpty()
{
List PtrL;
PtrL = (List)malloc(sizeof(struct LNode));
PtrL->Last=-1;
return PtrL;
}
//find X from list
int Find(double X, List PtrL)
{
int i=0;
while(i <= PtrL->Last && PtrL->Data[i] != X)
i++;
if(i > PtrL->Last)
{
printf("There is no such element in the list.\n");
return -1;
}
else
{
printf("The position of %.2f is %d.\n", X, i);
return i;
}
}
//insert x in list
void Insert(double X, int i, List PtrL)
{
int j;
if(PtrL->Last == MAXSIZE-1)
{
printf("List full!");
return;
}
if(i < 1 || i>PtrL->Last + 2)
{
printf("Location illegal.");
return;
}
for(j = PtrL->Last; j >= i-1; j--)
PtrL->Data[j+1] = PtrL->Data[j];
PtrL->Data[i-1] = X;
PtrL->Last++;
return;
}
//delete element at position i
void Delete(int i, List PtrL)
{
int j;
if(i < 1 || i > PtrL->Last+1)
{
printf("No %d element", i);
return;
}
for(j = i; j <= PtrL->Last; j++)
PtrL->Data[j-1]=PtrL->Data[j];
PtrL->Last--;
return;
}
- 主函数,调用线性结构头文件,实现线性表一系列具体操作。
//main.cpp
#include "structList.h"
using namespace std;
int main()
{
List mylist = MakeEmpty();
cout<<"Insert elements into the list。"<<endl;
for(int i=1;i<10;i++)
{
Insert(3.0*i-1.4,i,mylist);
}
cout<<endl;
cout<<"After insertation:"<<endl;
for(int i=0;i<mylist->Last;i++)
{
cout<<"Position "<<i<<" of list is "<<mylist->Data[i]<<endl;
}
cout<<"Find the position of "<<4.6<<endl;
Find(4.6, mylist);
cout<<endl;
cout<<"Find the position of "<<3.5<<endl;
Find(3.5, mylist);
cout<<endl;
cout<<"Delete element at position "<<4<<endl;
Delete(4,mylist);
cout<<endl;
cout<<"After deletion:"<<endl;
for(int i=0;i<mylist->Last;i++)
{
cout<<"Position "<<i<<" of list is "<<mylist->Data[i]<<endl;
}
return 0;
}
- 结果: