用c++写了一个顺序表的程序,如下
#ifndef SEQLIST_H_INCLUDED
#define SEQLIST_H_INCLUDED
using namespace std;
template <class T>
class seqList
{
private:
T * data;
int maxSize;
int last;
public:
seqList(int sz = 2);
~seqList();
bool Insert(int i, T & x);
bool Remove(int i, T & x);
int size() const{ return maxSize; }
void exchange();
void input();
};
template <class T>
seqList<T>::seqList(int sz)
{
maxSize=sz;
last=sz-1;
data = new T[maxSize];
}
template <class T>
seqList<T>::~seqList()
{
delete[] data;
}
template <class T>
bool seqList<T>::Insert(int i, T & x)
{
if (last == maxSize-1)
return false;
if(i<0 || i>last+1)
return false;
for(int j=last; j>=i-1; j--)
{
data[j+1]=data[j];
}
data[i-1]=x;
last++;
return true;
}
template <class T>
bool seqList<T>::Remove(int i, T & x)
{
if(last == -1)
return false;
if(i<1 || i>last+1)
return false;
x=data[i-1];
for(int j=i; j<=last; j++)
{
data[j-1]=data[j];
}
last--;
return true;
}
template <class T>
void seqList<T>::exchange()
{
int n = this->size();
if(n%2 == 0)
{
cout<<"位置置换之前的表为:"<<endl;
for(int j=0; j<n; j++)
{
cout<<data[j]<<" ";
}
cout<<endl;
T temp;
for(int j = 0; j < n/2; j++)
{
temp=data[j];
data[j]=data[n-1-j];
data[n-1-j]=data[j];
}
cout<<"位置置换后的表为:"<<endl;
for(int j=0; j<n; j++)
{
cout<<data[j]<<" ";
}
}
if(n%2 == 1)
{
cout<<"位置置换之前的表为:"<<endl;
for(int j=0; j<n; j++)
{
cout<<data[j]<<" ";
}
cout<<endl;
T temp;
for(int j=0; j<(n-1)/2; j++)
{
temp=data[j];
data[j]=data[n-1-j];
data[n-1-j]=data[j];
}
cout<<"位置置换后的表为:"<<endl;
for(int j=0; j<n; j++)
{
cout<<data[j]<<" ";
}
}
}
template <class T>
void seqList<T>::input()
{
cout<<"开始建立顺序表!"<<endl;
for (int i=0; i<maxSize; i++)
{
cout<<"请输入顺序表的第"<<i+1<<"个值:";
cin>>data[i];
}
cout<<"含有"<<maxSize<<"个值的顺序表建立成功!"<<endl;
}
#endif // SEQLIST_H_INCLUDED
#include <iostream>
#include "seqList.h"
using namespace std;
int main()
{
int n;
cout << "请输入表的长度:";
cin >> n;
seqList<int> sq(n);
sq.input();
sq.exchange();
return 0;
}
运行结果如下:
为什么会出现循环,我觉得代码没问题,也有可能是我真的不懂,还有,我用的是codeblock编辑器,不会调试程序,有大神愿意跟我说下比如这个程序改如何调试吗,谢谢!好人一生平安,授人以鱼不如授人以渔!