顺序表示线性表的一种,不像另一种链表那么神秘,顺序表其实离我们很近,它就是一个数组。
#ifndef MYQUEUE_H
#define MYQUEUE_H
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class List
{
public:
explicit List(int size);
~List();
void ClearList();
bool ListEmpty();
int ListLength();
bool GetElem(int i, int *e);
int LocateElem(int *e);
bool ListInsert(int i, int *e);
bool PriorElem( int *currentElem, int *preElem);
bool NextElem(int *currentElem, int *nextElem);
bool listDelete(int i, int *e);
void ListTraverse();
private:
int *m_plist;
int m_size;
int m_length;
};
List::List(int size)
{
m_size = size;
m_length = 0;
m_plist = new int[m_size];
}
List::~List()
{
delete []m_plist;
m_plist = NULL;
}
void List::ClearList()
{
m_length = 0;
}
bool List::ListEmpty()
{
if (m_length == 0)
return true;
else
return false;
}
int List::ListLength()
{
return m_length;
}
bool List::GetElem(int i,int *e)
{
if (i < 0 || i >= m_size)
return false;
else
{
*e = m_plist[i];
return true;
}
}
int List::LocateElem(int*e)
{
for (int i(0); i < m_length; ++i)
{
if (*e == m_plist[i])
return i;
}
return -1;
}
bool List::ListInsert(int i, int *e)
{
if (i < 0 || i > m_length)
return false;
else
{
for (int k=m_length -1; k >= i; --k)
{
m_plist[k + 1] = m_plist[k];
}
m_plist[i] = *e;
m_length++; // 这一步容易忘
return true;
}
}
bool List::PriorElem(int *currentElem, int *preElem)
{
int i = 0;
i = LocateElem(currentElem);
if (i = -1)
return false;
else
{
if (i=0)
{
return false;
}
else
{
*preElem = m_plist[i - 1];
return true;
}
}
}
bool List::NextElem(int *currentElem, int *nextElem)
{
int i = 0;
i = LocateElem(currentElem);
if (i = -1)
return false;
else
{
if (i = m_length-1)
{
return false;
}
else
{
*nextElem = m_plist[i + 1];
return true;
}
}
}
bool List::listDelete(int i, int *e)
{
*e = m_plist[i];
if (i < 0 || i >= m_length)
return false;
else
{
for (int k(i + 1); k < m_length; ++k)
{
m_plist[k - 1] = m_plist[k];
}
m_length--; //容易遗落这条语句
return true;
}
}
void List::ListTraverse()
{
for (int i(0); i < m_length; ++i)
{
cout << m_plist[i] << endl;
}
}
#endif
相较于栈和队列来说,成员函数多了 插入 、获取前驱和后继,删除、获取指定位置元素、 返回指定元素的第一个位置。