本篇讲述c++如何实现线性表中的顺序表,即用数组的方式实现。
头文件中的内容如下:
class List
{
public:
List(int capacity);
~List();
int Length();
void ClearList(); //清空链表
bool IsEmpty();
bool IsFull();
bool GetElem(int i, int *e); //获取第i个位置上的元素
int LocateElem(int ele);
bool GetPredecessor(int ele, int *e); //获取目标元素的前驱
bool GetSuccessor(int ele, int *e); //获取目标元素的后继
bool TraverseList();
bool ListInsert(int loc, int ele); //当前位置插入元素
bool ListDelete(int loc, int *e); //当前位置删除元素
private:
int *m_pList;
int m_iCapacity;
int m_iLen;
};
源文件中的内容如下:
#include <iostream>
#include "List.h"
using namespace std;
List::List(int capacity)
{
m_iCapacity = capacity;
m_pList = new int[m_iCapacity];
m_iLen=0;
}
List::~List()
{
delete []m_pList;
m_pList = NULL;
}
int List::Length()
{
return m_iLen;
}
void List::ClearList()
{
m_iLen = 0;
}
bool List::IsEmpty()
{
return m_iLen == 0 ? true : false;
}
bool List::IsFull()
{
return m_iLen == m_iCapacity ? true : false;
}
bool List::GetElem(int i, int *e)
{
if (i < 0 || i >= m_iCapacity){
return false;
}
*e = m_pList[i];
return true;
}
int List::LocateElem(int ele)
{
for (int i = 0; i < m_iLen; i++){
if (m_pList[i] == ele){
return i;
}
}
return -1; //not find
}
bool List::GetPredecessor(int ele, int *e)
{
int loc = LocateElem(ele);
if (loc == -1 || loc == 0){
return false;
}
else{
*e = m_pList[loc-1];
return true;
}
}
bool List::GetSuccessor(int ele, int *e)
{
int loc = LocateElem(ele);
if (loc == -1 || loc == m_iLen-1){
return false;
}else{
*e = m_pList[loc+1];
return true;
}
}
bool List::TraverseList()
{
if (m_iLen == 0){
return false;
}else{
for (int i = 0; i < m_iLen; i++){
cout << m_pList[i] << endl;
}
return true;
}
}
bool List::ListInsert(int loc, int ele)
{
if (IsFull()){
return false;
}else{
if (loc >= 0 && loc <= m_iLen){
for (int i = m_iLen - 1; i >= loc; i--){
m_pList[i + 1] = m_pList[i];
}
m_pList[loc] = ele;
m_iLen++;
return true;
}else{
return false;
}
}
}
bool List::ListDelete(int loc, int *e)
{
if (IsEmpty()){
return false;
}else{
if (loc >= 0 && loc <= m_iLen-1){
*e = m_pList[loc];
for (int i = loc; i < m_iLen - 1; i++){
m_pList[i] = m_pList[i + 1];
}
m_iLen--;
return true;
}else{
return false;
}
}
}
测试程序如下:
#include <iostream>
#include "List.h"
using namespace std;
int main(void)
{
List *p = new List(5);
p->ListInsert(0, 3);
p->ListInsert(1, 5);
p->ListInsert(2, 7);
p->ListInsert(3, 9);
p->ListInsert(4, 11);
p->ListInsert(5, 13);
p->TraverseList();
cout << endl;
int temp = 0;
p->ListDelete(2, &temp);
p->ListDelete(2, &temp);
p->TraverseList();
cout << endl;
delete p;
p = NULL;
system("pause");
return 0;
}