.h
#pragma once
#ifndef _LIST_H
#define _LIST_H
class List
{
public:
List(int size);
virtual ~List();
void ClearList();
bool ListEmpty()const;
int ListLength()const;
bool GetElem(int i, int &element)const;
int LocateElem(int element) const;
bool PriorElem(int curr, int *pre)const;
bool NextElem(int curr, int *nex)const;
bool EnList(int addr,int element);
bool DeList(int addr,int &element);
void ListTraverse()const;
private:
int *m_pList;
int m_iSize;
int m_iLength;
};
#endif
.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()const
{
return m_iLength == 0 ? true : false;
}
int List::ListLength()const
{
return m_iLength;
}
bool List::GetElem(int i, int &element)const
{
if (i >= 0 && i < m_iSize)
{
element = m_pList[i];
}
else
return false;
return true;
}
int List:: LocateElem(int element)const
{
for (int i = 0; i < m_iLength; i++)
{
if (m_pList[i] == element) { return i; }
}
return -1;
}
bool List::PriorElem(int curr, int *pre)const
{
int temp = LocateElem(curr);
if (temp == -1 || temp == 0) { return false; }
else
{
*pre = m_pList[temp - 1];
}
return true;
}
bool List::NextElem(int curr, int *nex)const
{
int temp = LocateElem(curr);
if (temp == -1 || temp == m_iLength ) { return false; }
else
{
*nex = m_pList[temp + 1];
}
return true;
}
void List::ListTraverse()const
{
for (int i = 0; i < m_iLength; i++)
{
cout << m_pList[i] << endl;
}
}
bool List::EnList(int addr, int element)
{
if (m_iLength == m_iSize || addr > m_iLength + 1 || addr < 0) return false;
for (int i = m_iLength; i > addr; i--)
{
m_pList[i + 1] = m_pList[i];
}
m_pList[addr] = element;
m_iLength++;
return true;
}
bool List::DeList(int addr,int &element)
{
if (addr < 0 || addr >= m_iLength || m_iLength == 0) return 0;
element = m_pList[addr];
for (int i = addr + 1; i < m_iLength; i++)
{
m_pList[i - 1] = m_pList[i];
}
m_iLength--;
return true;
}
#main
include “list.h”
#include "list.h"
using namespace std;
int main(void)
{
List *p = new List(4);
p->EnList(0, 2);
p->EnList(1, 3);
p->EnList(2, 5);
p->EnList(3, 2);
p->ListTraverse();
int tem = 0;
p->DeList(1, tem);
cout << tem << endl;
p->ClearList();
delete p;
p = NULL;
system("pause");
return 0;
}
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/386da5e5c0d419b1bbf9f06578f7ddfa.png)