提要:這是我新開的一個專欄(數據結構學習)
很多的數據結構的書籍都是以C爲基礎實現的,主要是由於C強大的指針功能,我本人看的也是C語言版本,但是我是用C++實現的。建議以後想要學習C++的小夥伴最好也能把數據結構的內容從頭至尾自己都實現一遍,不管用什麼語言,因爲數據結構在以後找工作的時候是必問知識
這是本專欄的第一篇內容 介紹的是線性表的順序存儲結構以及C++實現方法,話不多說,下面就開始的線性表的學習:
首先是頭文件部分:
#pragma once
#include <iostream>
#define MAXSIZE 100
using namespace std;
template <class ElemType>
class CList
{
public:
CList();
virtual ~CList();
int getLen();
int getSize();
bool insertElem(const int &i, const ElemType &e);
void showValue();
ElemType getElem(int i);
void deletElem(int i);
void modify(int i,const ElemType &e);
ElemType *baseAddress;
int m_length;
int m_size;
};
其次是核心代碼部分(函數的定義)
#include "list.h"
template <class ElemType>
CList<ElemType>::CList()
{
m_size = 0;
m_length = MAXSIZE;
baseAddress = new ElemType[MAXSIZE];
}
template <class ElemType>
CList<ElemType>::~CList()
{
delete[] baseAddress;
}
template <class ElemType>
int CList<ElemType>::getLen()
{
return m_length;
}
template <class ElemType>
int CList<ElemType>::getSize()
{
return m_size;
}
template <class ElemType>
bool CList<ElemType>::insertElem(const int &i, const ElemType &e){
if (m_size == MAXSIZE) {
cout << "線性表已滿,不能插入元素" << endl;
return false;
}else if (i < 1 || i >= MAXSIZE) {
cout << "請輸入正確的插入位置" << endl;
return false;
}else {
for (int index = m_size - 1; index >= i - 1; --index) {
baseAddress[index + 1] = baseAddress[index];
}
baseAddress[i - 1] = e;
m_size++;
return true;
}
}
template<class ElemType>
ElemType CList<ElemType>::getElem(int i)
{
if (i < 1 || i > m_size) {
cout << "請輸入正確的查找位置" << endl;
}
else {
return baseAddress[i - 1];
}
}
template<class ElemType>
void CList<ElemType>::deletElem(int i)
{
;
if (!m_size) {
cout << "線性表爲空" << endl;
return;
}
else if (i < 1 || i > m_size) {
cout << "要刪除的位置不在可行範圍之內" << endl;
return;
}
else {
ElemType e = baseAddress[i - 1];
for (int index = i; index != m_size; ++index) {
baseAddress[index - 1] = baseAddress[index];
}
m_size--;
}
}
template<class ElemType>
void CList<ElemType>::showValue(){
if (m_size == 0) {
cout << "表中無元素" << endl;
return;
}else {
for (int index = 0; index < m_size; ++index) {
cout << baseAddress[index] << " ";
}
cout << endl;
}
}
template <class ElemType>
void CList<ElemType>::modify(int i, const ElemType &e) {
if (i < 1 || i >= m_size) {
cout << "請輸入正確的位置" << endl;
return;
}
baseAddress[i - 1] = e;
}
最後是測試部分(主函數)
#include "list.cpp"
using namespace std;
int main()
{
CList<int> lst;
cout << "空表的中的元素個數" << lst.getSize() << endl;
cout << "空表分配的內存空間" << lst.getLen() << endl;
for (int i = 1,j=9; i < 10; ++i,--j) {
lst.insertElem(i,j);
}
lst.showValue();
cout << lst.getElem(1) << endl;
lst.deletElem(1);
cout << "作刪除操作後的線性表" << endl;
lst.showValue();
lst.modify(1,9);
lst.showValue();
system("pause");
return 0;
}