c++写数据结构

来源:百度知道 编辑:UC知道 时间:2024/07/15 23:57:45
从键盘输入两个单链表A和B,其表中元素递减有序,编写程序将A和B归并成一个按元素值递减有序的单链表C。分别输出单链表A、B和C所有结点的值。
我的头文件是struct Node
{
int data;
Node *next;
};
class List
{
public:
List();
~List();
void input();
void output();
void mergelist(List *La,List *Lb,List *&LC);
private:
Node *head;
};
实现是#include"head.h"
#include"iostream.h"
List::List()
{
head=new Node;
head->next=NULL;
}
List::~List()
{}
void List::input()
{
Node *p1,*p2;
cout<<"请输入数据"<<endl;
p1=new Node;
head->next=p1;
cin>>p1->data;
p1->next=NULL;
while(p1->data)
{
p2=new Node;
p1->next=p2;
p1=p2;
cin>>p1->data;
}
p2->next=NULL;
}
void List::output()
{
Node *p=head->next;
cout<<"输出的数为"<<endl;

w

我看一看,两三天后回复~~

我建议你使用C++STL,既简单,速度快,出错率还少:
虽然可以用<algorithm>中的泛型算法,但是对于链表不建议使用其中的sort类算法,因为list在访问时有不可避免的缺陷。

#include <list>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

int main ()
{
list<int> a;
for (int i = 10; i != 0; --i)
a.push_back(i);
a.sort(greater<int>());
list<int> b;
for (int i = 10; i != 20; ++i)
b.push_back(i);
b.sort(greater<int>());
//
b.merge(a, greater<int>());
copy (b.begin(), b.end(), ostream_iterator<int>(cout, "\t"));
}

如果你要求过程,这可能对你来说没用!但是这是一种编程的好做法!