首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

C++ 数构 关于两个顺序表合并的有关问题

2012-02-25 
C++ 数构 关于两个顺序表合并的问题题目为:有两个顺序表LA和LB,其元素均为非递减有序排列,编写一个算法,将

C++ 数构 关于两个顺序表合并的问题
题目为:有两个顺序表LA和LB,其元素均为非递减有序排列,编写一个算法,将它们合并成一个顺序表LC,要求LC也是非递减有序排列。例如LA=(2,2,3),LB=(1,3,3,4),则LC=(1,2,2,3,3,3,4)。 
先输入一个T表示有若T种案例(T<100)。每种案例的第一行先输入一个正整数m,表示LA表中有m个数据,接着有m个数据;然后是输入一个正整数n,再接着是n个数据。1<=m、n<100 000。如果一行的数据超出100个,就会换行。对每个案例先输入一行“Case id:”,第二行开始输出合并后的线性表,数据之间用空格隔开。

下面是我写的代码,但是运行时有些错误

#include <iostream.h>
template <class T>
class LinearList
{
public:

 virtual int Length() const = 0;
 virtual bool Insert(int i,T x) = 0;

 virtual void Output(ostream& out,int id) const = 0;

protected:

 int n;

};

template <class T>

class SeqList:public LinearList<T>

{

public:

 SeqList(int mSize);

 int Length() const;

 bool Insert(int i,T x);

 void Output(ostream& out,int id) const;

public:

 int maxLength;

 T *elements;

};

template <class T>

SeqList<T>::SeqList(int mSize)

{

 maxLength = mSize;

 elements = new T[maxLength];

 n = 0;

}

template <class T>

int SeqList<T>::Length() const

{

 return n;

}

template <class T>

bool SeqList<T>::Insert(int i,T x)

{

 if(i < -1 || i > n - 1)

 {

  cout<<"Out of Bounds"<<endl;

  return false;

 }

 if(n == maxLength)

 {

  cout<<"OverFlow"<<endl;

  return false;

 }

 for(int j = n - 1;j > i;j--)

 {

  elements[j + 1] = elements[j];

 }

 elements[i + 1] = x;

 n++;

 return true;

}

template <class T>

void SeqList<T>::Output(ostream& out,int id) const

{

 cout<<"Case "<<id<<":"<<endl;

 for(int i = 0;i < n;i++)

 {

  out<<elements[i]<<" ";

 }

 out<<endl;

}

template <class T>

void Hebing(SeqList<T> &LA,SeqList<T> &LB,SeqList<T> &LC)

{

 int x,y;

 for(x=0,y=0;x<LA.Length() && y<LB.Length();)

 {

  if(LA.elements[x]<LB.elements[y])

  {

  LC.Insert(LC.Length()-1,LA.elements[x]);

  x++;

  }

  else

  {

  LC.Insert(LC.Length()-1,LB.elements[y]);

  y++;

  }

 }

  if(x=LA.Length())

  {

  while(y<LB.Length())

  {

  LC.Insert(LC.Length()-1,LB.elements[y]);

  y++;

  }

  }

  else

  {

  while(x<LA.Length())

  {

  LC.Insert(LC.Length()-1,LA.elements[x]);

  x++;
  }
  }
}

void main()


  double p,q;

 int n,m,t,count=0; 

 cin>>t;

 while(t)
 {

 cin>>n;

  SeqList<double> LA(n);

 for(int i = 0;i < n;i++)

 {

  cin>>p;

  LA.Insert(i - 1,p);



 }
  cin>>m;SeqList<double> LB(m);

 for(int j = 0;j < m;j++)

 {

  cin>>q;

  LB.Insert(j - 1,q);

 }

 int s;

 s=n+m;

  SeqList<double> LC(s);

 Hebing(LA,LB,LC);

 count++;

 if(count==100)

 {

  cout<<endl;

 LC.Output(cout,count);

 }

 else

  LC.Output(cout,count);


 t--;

 }


}


当我输入
3
34 55 999
2
76 899
时显示的结果是 34 55 76 899
少了999,应该是Hebing函数有问题,但是我不知道该怎么改,请大家帮忙看看,谢谢!

[解决办法]
一开始看你的代码风格挺不错的,觉得你应该很细心。呵呵 这次却犯了一个低智商错误。
if(x=LA.Length()) //此处改为x==LA.Length()

{

while(y<LB.Length())

{

LC.Insert(LC.Length()-1,LB.elements[y]);

y++;

}

}

热点排行