本文主要是介绍数据冒险之顺序表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
List.h
#ifndef LIST_H
#define LIST_H
/******顺序表*****/
class List
{
public:List(int size); //创建线性表 ~List(); //销毁线性表 void ClearList(); //清空 bool ListEmpty(); //判空 int ListLength(); //获取线性表长度 bool GetElem(int i, int *e); //获取指定元素 int LocateElem(int *e); //定位元素 寻找第一个满足e的元素的位序 bool PriorElem(int *currentElem, int *preElem);//获取指定元素的前驱 bool NextElem(int *currentElem, int *nextElem);//获取指定元素的后继 void ListTraverse(); //遍历线性表 bool ListInsert(int i, int *e); //在第i个位置插入元素 bool ListDelete(int i, int *e); //删除第i个位置的元素
private:int *m_pList; int m_iSize; int m_iLength; //当前已放入元素长度
};
#endif
List.cpp
#include<iostream>
#include"List.h"
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 (0 == m_iLength)return true;elsereturn false;}
int List::ListLength()
{return m_iLength;
}
bool List::GetElem(int i, int *e)
{if (i<0 || i >= m_iSize)return false;else*e = m_pList[i];return true;
}
int List::LocateElem(int *e)
{for (int i = 0; i<m_iLength; i++){if (m_pList[i] == *e)return i;}return -1;
}bool List::PriorElem(int *currentElem, int *preElem) //前驱
{int temp = LocateElem(currentElem); //当前元素下标if (-1 == temp) //当前元素不存在return false;else{if (0 == temp) //当前元素为第一个元素,不存在前驱return false;else //当前元素存在前驱{*preElem = m_pList[temp - 1];return true;}}
}
bool List::NextElem(int *currentElem, int *nextElem)
{int temp = LocateElem(currentElem);if (-1 == temp) //当前元素不存在return false;else{if ((m_iLength - 1) == temp) //当前元素为最后一个元素,不存在后驱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, int *e) //插入操作,先移动再插入
{if (i<0 || i>m_iLength) //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, int *e) //删除操作,先删除再移动
{if (i<0 || i >= m_iLength) return false;*e = m_pList[i];for (int k = i + 1; k<m_iLength; k++) //从第i+1个元素开始移动{m_pList[k - 1] = m_pList[k];}m_iLength--;return true;
}
main.cpp
#include <iostream>
#include "List.h"
using namespace std;int main(void)
{List *List1 = new List(8);int e1 = 1;int e2 = 2;int e3 = 3;int e4 = 4;int e5 = 5;int e6 = 6;int e7 = 7;//插入cout << "插入的元素:" << endl;List1->ListInsert(0, &e1);List1->ListInsert(1, &e2);List1->ListInsert(2, &e3);List1->ListTraverse();cout << "已有元素的length:" << List1->ListLength() << endl;List1->ListInsert(3, &e4);List1->ListInsert(4, &e5);List1->ListInsert(5, &e6);List1->ListInsert(6, &e7);List1->ListTraverse();//删除cout << "删除的元素:" << endl;int temp = 0;List1->ListDelete(5, &temp);List1->ListTraverse();cout << "删除元素为: " << temp << endl;delete List1;List1 = NULL;return 0;
}
这篇关于数据冒险之顺序表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!