您的位置:首页 > 理论基础 > 数据结构算法

简单数据结构-数组实现线性表

2016-04-20 10:31 453 查看
/*
* File name  : List.cpp
* Function   :
* Created on : 2016年4月19日
* Author     : beijiwei@qq.com
* Copyright  : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。
任何单位和个人不经本人允许不得用于商业用途
*/
#include <cstdio>
#include <iostream>

using namespace std;

#define MAX 10

typedef struct{
int array[MAX];
int length;
}List;

void list_init(List &L);
void list_clear(List &L);
bool list_is_empty(List &L);
bool list_insert(List &L, int i, int elem);
bool list_delete(List &L, int i);
bool list_get(List &L, int i,int &elem);
int  list_search(List &L, int elem);
int  list_get_length(List &L);

int main(int argc, char** argv)
{
List one;
list_init(one);
cout<<"List one is empty ? "<<list_is_empty(one)<<endl;
cout<<"The length of List one is :"<<list_get_length(one)<<endl;
for(int i=0;i<=MAX;i++)
{
list_insert(one,i,i+10);
}
cout<<"\n\n\n";
cout<<"List one is empty ? "<<list_is_empty(one)<<endl;
cout<<"The length of List one is :"<<list_get_length(one)<<endl;

cout<<"The elem in List one is:"<<endl;
for(int i=0;i<list_get_length(one);i++)
{	int elem;
list_get(one,i,elem);
cout<<elem<<"\t";
}
list_delete(one,4);
cout<<endl<<"The length of List one is :"<<list_get_length(one)<<endl;
cout<<"The elem in List one is:"<<endl;

for(int i=0;i<list_get_length(one);i++)
{	int elem;
list_get(one,i,elem);
cout<<elem<<"\t";
}

list_delete(one,1);
cout<<endl<<"List one is empty ? "<<list_is_empty(one)<<endl;
cout<<"The length of List one is :"<<list_get_length(one)<<endl;
cout<<"The elem in List one is:"<<endl;
for(int i=0;i<list_get_length(one);i++)
{	int elem;
list_get(one,i,elem);
cout<<elem<<"\t";
}

return 0;
}

void list_init(List &L)
{
L.length=0;
}

void list_clear(List &L)
{
L.length=0;
}

bool list_is_empty(List &L)
{
return (L.length==0) ? true : false;
}

bool list_insert(List &L, int k,int elem)
{
if( k<0 || k>L.length+1 || k>MAX-1)
return false;
if(L.length==MAX)
return false;

for(int i=L.length;i>k;i--)
{
L.array[i]=L.array[i-1];
}
L.array[k]=elem;
L.length++;
return true;

}
bool list_delete(List &L, int k)
{
if(k>=L.length || k<0 || L.length==0)
return false;
for(int i=k;i<L.length-1;i++)
{
L.array[i]=L.array[i+1];
}
L.length--;
return true;
}
bool  list_get(List &L, int i, int &elem)
{
if(i>L.length-1 || i<0 || L.length==0)
return false;
elem=L.array[i];
return true;
}

int  list_search(List &L, int elem)
{
if(L.length==0)
return -1;
for(int i=0;i< L.length;i++)
{
if(elem==L.array[i])
return i;
}
return -1;
}
int list_get_length(List &L)
{
return L.length;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: