//sequence.cpp
#include <iostream>
#include "sequence.h"
using namespace std;
Arr::Arr(int * phead,int len,int curlen)
{
m_phead = phead;
m_len = len;
m_curlen = curlen;
}
Arr::~Arr()
{
delete [] m_phead;
}
bool Arr::init()
{
cout<<"输入你想建立的顺序表的大小:\n";
m_len = getValue();
m_phead = new int[m_len];
m_curlen = 0;
if(m_phead == NULL)
return false;
else
return true;
}
bool Arr::insert(int value,int position)
{
if(m_phead == NULL)
{
cout<<"请先初始化顺序表!\n";
}
else if(m_curlen+1 > m_len)
{
cout<<"顺序表已满,不能再添加元素!\n";
return false;
}
else if(position > m_curlen)
{
cout<<"元素插入位置错误!\n";
return false;
}
else
{
int i = m_curlen;
while(i>position)
{
m_phead[i] = m_phead[i-1];
i--;
}
m_phead[i] = value;
m_curlen++;
return true;
}
}
bool Arr::add(int value)
{
return insert(value,m_curlen);
}
void Arr::show()
{
for(int i=0;i<m_curlen;i++)
{
cout<<m_phead[i]<<" ";
}
cout<<endl;
}
bool Arr::deleteValue(int position)
{
if(m_curlen == 0)
{
cout<<"顺序表为空,无法删除!\n";
return false;
}
else if(position>m_curlen)
{
cout<<"元素位置输入错误!\n";
return false;
}
else
{
int i = position-1;
while(i<m_curlen-1)
{
m_phead[i] = m_phead[i+1];
i++;
}
m_curlen--;
return true;
}
}
int Arr::getValue()
{
int i = 0;
bool b = true;
while(b)
{
if(!(cin>>i))
{
cout<<"你输入的有误,请重新输入:\n";
cin.clear();
}
else
{
b = false;
}
while(cin.get() != '\n')
continue;
}
return i;
}
//sequence.h
#ifndef SEQUENCE_H
#define SEQUENCE_H
#include <iostream>
class Arr
{
private:
int * m_phead;
int m_len;
int m_curlen;
public:
Arr(int * phead = NULL,int len = 0,int curlen = 0);
~Arr();
int getValue();
bool init();
bool insert(int value,int position);
bool add(int value);
void show();
bool deleteValue(int position);
};
#endif SEQUENCE_H
//main.cpp
#include "sequence.h"
#include <iostream>
using namespace std;
int main()
{
Arr arr;
int i;
int value;
int position;
int count = 0;
cout<<"********************************************************************************";
cout<<"\t\t\t数据结构-用c++语言实现顺序表\n";
while(1)
{
cout<<"********************************************************************************";
cout<<"\t\t\t\t1、初始化顺序表\n\t\t\t\t2、添加元素\n\t\t\t\t3、删除元素\n\t\t\t\t4、插入元素\n\t\t\t\t5、显示数组中的元素\n\t\t\t\t6、退出\n";
cout<<"********************************************************************************";
i = arr.getValue();
switch(i)
{
case 1:
count++;
if(count == 1)
arr.init();
else
{
cout<<"顺序表只能进行一次初始化!\n";
}
break;
case 2:
cout<<"输入你想添加的元素:\n";
value = arr.getValue();
if(!arr.add(value))
{
cout<<"元素添加失败!\n";
}
break;
case 3:
cout<<"输入你想删除元素的位置:\n";
position = arr.getValue();
arr.deleteValue(position);
break;
case 4:
cout<<"输入你想添加的元素:\n";
value = arr.getValue();
cout<<"你想在何处插入该元素:\n";
position = arr.getValue();
if(!arr.insert(value,position-1))
{
cout<<"元素插入失败!\n";
}
break;
case 5:
arr.show();
break;
case 6:
exit(1);
break;
default:
cout<<"你的选择错误,请重新选择:\n";
}
}
return 0;
}
顺序表(c++版)
最新推荐文章于 2024-05-14 22:04:37 发布