顺序表:与数据元素在计算机内“物理位置相邻”来表示线性表中数据元素之间的逻辑关系。
具有随机存取的特点。
代码实现:
List.h
#ifndef LIST_H
#define LIST_H
typedef int Elem;
class List
{
public:
List(int size);
~List();
void ClearList(); //清空顺序表
bool ListEmpty();
int ListLength();
bool GetElem(int i, Elem *e);
int LocationElem(Elem *e);
bool PriorElem(Elem *currentElem,Elem *preElem);
bool NextElem(Elem *currentElem, Elem *nextElem);
void ListTraverse();
bool ListInsert(int i,Elem *e);
bool ListDelete(int i, Elem *e);
private:
int *m_pList;
int m_iSize;
int m_iLength;
};
#endif
List.cpp
#include"List.h"
#include<iostream>
using namespace std;
List::List(int size)
{
m_iSize = size;
m_pList = new int[m_iSize];
m_iLength = 0;
}
List::~List()
{
delete[] m_pList;
m_pList = NULL;
}
void List::ClearList(){
m_iLength = 0;
}
bool List::ListEmpty(){
/*if (m_iLength == 0)
return true;
else return false; */
return m_iLength == 0 ? true : false;
}
int List::ListLength(){
return m_iLength;
}
bool List::GetElem(int i, Elem *e){
if (i<0||i>=m_iSize){
return false;
}
e = m_pList;
return true;
}
int List::LocationElem(Elem *e){
for (int i = 0; i < m_iLength;i++){
if (m_pList[i] == *e)
{
return i;
}
}
return -1;
}
bool List::PriorElem(Elem *currentElem, Elem *preElem){
int temp= LocationElem(currentElem);
if (temp==-1){
return false;
}
else{
if (temp == 0)
return false;
else{
*preElem = m_pList[temp-1];
return true;
}
}
}
bool List::NextElem(Elem *currentElem, Elem *nextElem){
int temp = LocationElem(currentElem);
if (temp == -1){
return false;
}
else{
if (temp == m_iLength-1)
return false;
else{
*nextElem = m_pList[temp +1];
return true;
}
}
};
void List::ListTraverse(){
for (int i = 0; i < m_iLength; i++)
cout << m_pList[i] << endl;
};
bool List::ListInsert(int i, Elem *e){
if (i<0 || i>m_iLength)
return false;
//先移动--倒叙,后插值
for (int k = m_iLength-1; k >=i; k--){
m_pList[k + 1] = m_pList[k];
}
m_pList[i] = *e;
m_iLength++;
return true;
};
bool List::ListDelete(int i, Elem *e){
if (i<0 || i>=m_iLength)
return false;
//先删除--再移动
*e = m_pList[i];
for (int k = i + 1; k < m_iLength;k++){
m_pList[k - 1] = m_pList[k];
}
m_iLength--;
return true;
};
主函数:
#include<iostream>
#include<stdlib.h>
#include"List.h"
using namespace std;
int main1(void){
int e1 = 3;
int e2 = 5;
int e3 = 7;
int e4 = 2;
int e5 = 9;
int e6 = 1;
int e7 = 8;
int temp=0;
List *list1 = new List(10);
list1->ListInsert(0,&e1);
list1->ListInsert(1, &e2);
list1->ListInsert(2, &e3);
list1->ListInsert(3, &e4);
list1->ListInsert(4, &e5);
list1->ListInsert(5, &e6);
list1->ListInsert(3, &e7);
list1->ListDelete(0, &temp);
if (!list1->ListEmpty()){
cout << "not empty" << endl;
};
list1->ClearList();
if (list1->ListEmpty()){
cout << "empty" << endl;
};
list1->ListTraverse();
cout<< "#" << temp << endl;
delete list1;
system("pause");
return 0;
}