在繁忙的工作中,回忆一下大学的数据结构,重新码一下,温故而知新
线性表的优缺点:
优点 | 缺点 |
无须为表中元素之间的逻辑关系而增加额外的存储空间 | 插入和删除操作需要移动大量的元素 |
可以快速的存取表中任意位置的元素 | 当线性表长度变化较大时,难以控制存储空间的容量 |
造成存储空间的‘碎片’ | |
先上码:
linerList.hpp:
#ifndef LINERLIST_HPP_
#define LINERLIST_HPP_
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
template <class T>
class LinerList
{
public :
LinerList();
void destroy();
void clear();
bool isEmpty();
int size();
T getElem(int i,T &e);
int getFirstPosition(T e);
T getPriorElem(T cur_e,T &pre_e);
T getNextElem(T cur_e,T &next_e);
void insert(int i,T e);
T remove(int i,T &e);
private:
T *elem;
int length;
int listsize;
};
#endif
linerList.cpp:
#include "linerList.hpp"
#include<stdlib.h>
#include<iostream>
using namespace std;
template <class T>
LinerList<T>::LinerList()
{
elem=(T *)malloc(LIST_INIT_SIZE*sizeof(T)); /*分配空间*/
if(!elem)
throw "Allocation failed";
else
{
length=0;
listsize=LIST_INIT_SIZE;
}
}
template <class T>
void LinerList<T> :: destroy()
{
free(elem);
}
template <class T>
void LinerList<T> :: clear()
{
length = 0;
}
template <class T>
void LinerList<T> :: insert(int i,T e)
{
if(i<0 || i>length+1)
{
cout << "Error:insert position invalid!"<<endl;
}
//judge position is the last
if(i == length)
{
//increase size of 1
elem = (T *)realloc(elem,(length+10)*sizeof(T));
listsize += 10;
}
//移位
for(int j=length;j>=i;j--)
{
elem[j]=elem[j-1];
}
//插入
elem[i-1]=e;
length++;
}
template <class T>
T LinerList<T> :: remove(int i,T &e)
{
if(i<0 || i>length)
{
throw "indexException:out of bounds :(";
}
else if( 0 == i)
{
throw "the Liner list is null now :(";
}
else{
e=elem[i-1];
for(int pos=i;pos<=length;pos++)
{
elem[pos-1] = elem[pos];
}
length --;
return e;
}
}
template <class T>
T LinerList<T> :: getElem(int i,T &e)
{
if(i<0 || i>length)
{
throw "indexException:out of bounds";
}else{
return elem[i-1];
}
}
template <class T>
int LinerList<T> :: getFirstPosition(T e)
{
for(int i=0;i<length;i++)
{
if(e == elem[i])
{
return i+1;
}
}
cout << "null excption :(" << endl;
return 0;
}
template <class T>
T LinerList<T> :: getPriorElem(T cur_e,T &e)
{
int firstPos = getFirstPosition(cur_e);
if(firstPos > 1)
{
return elem[firstPos -2];
}
else return NULL;
}
template <class T>
T LinerList<T> :: getNextElem(T cur_e,T &e)
{
int firstPos = getFirstPosition(cur_e);
if(firstPos < length && firstPos > 0 )
{
return elem[firstPos];
}
else return NULL;
}
template <class T>
int LinerList<T> :: size()
{
return length;
}
template <class T>
bool LinerList<T> :: isEmpty()
{
return length>0?false:true;
}
int main(int argc, char** argv)
{
LinerList<int> l;
int a[100];
for(int i =0 ; i < 100;i++)
{
l.insert(i+1,i+1);
}
/* cout << "before remove size : "<< l.size() <<endl;
cout << "remove num : " << l.remove(20,a[20])<<endl;
cout << "after remove size : " << l.size() << endl;
cout << "is empty ? " << l.isEmpty() << endl;*/
cout << "get position : " << l.getFirstPosition(0) << endl;
}