封装了指针的链表
											
程序代码:
#include<iostream>
#include<cassert>
using namespace std;
//既然允许全局了,就不用封装当前指针了。
//然而C++希望封装指针,所以建议不用全局head,而是定义一个
//表类和一个节点类。一张表就定义一个表的对象
//定义节点类,这只是一个节点!!!而不是一张表
class Node
{
public://这里可以定义为私有(保护)类型,
//多加几个函数就行,比较符合封装思想
    int exp;//指数
    float coef;//系数
    Node *next;
    Node(int ep,float cf,Node*p=NULL):exp(ep),coef(cf),next(p){}//cf为系数,ep为指数
    Node();
    ~Node(){}
    //void build(int,float);
    //void output();//题目未要求 不过可以用来测试
};
//定义表
/*不要弄混概念,在一个节点的构造函数中不可能初始化一张表!
    因为在构造函数中,这个节点还没有创建完成*/
class list{
private:
    Node*head;
    Node*curr;
public:
    list();//这个构造函数里可以进行所需的初始化
    ~list();
    void clear();//清除
    void build(int&,float&);//创建
    void display();//输出
    //bool is_empty();
    //bool is_full();
    //void insert();
    //这些没要求就不写了
};
//Node *head=NULL;  //已经封装了head
//题目要求的是在构造函数里面进行初始化
list::list(){   
    int exp_;
    float coef_;
   
    do{
    cout<<"please input exp : ";
    cin>>exp_;
    cout<<"please input coef : ";
    cin>>coef_;
    if(!cin.good()){cout<<"the end"<<endl;break;}
    if (head == NULL)  
    {head=new Node(exp_,coef_);}
    else
    { build(exp_,coef_);}
    }while(cin.good());
}
void list::build(int &ep,float &cf)//插入,合并同类项(虽然不符合异常安全)
{
    Node*p=new Node(ep,cf);
    assert(p!=head);   
    curr=head;
    assert(head!=NULL);
    if(ep>curr->exp){p->next=head;head=p;}else
    if(ep==curr->exp){curr->coef+=cf;/*cout<<"coef"<<curr->coef<<endl;*/}else{  
     while(curr!=NULL){
        if(ep>=curr->exp)break;//为了插入到和它相同指数的数之前
             if(curr->next==NULL){curr->next=new Node(ep,cf,curr->next);return;}
        curr=curr->next;
     }
    Node* Ix=head;
    while(Ix->next!=curr)Ix=Ix->next;//这个地方有点不舒服,不知道有没有高效点的算法
         if(curr->exp==p->exp){curr->coef+=cf;}else{
     p->next=curr;
     Ix->next=p;}
    }
}
Node::Node(){}
//释放链表
list::~list(){clear();}
void list::clear(){
    if(head!=NULL){
        curr=head;
        head=head->next;
        delete curr;       
        }
}
void list::display()
{
    curr=head;
    while (curr != NULL)
    {
        cout<<curr->coef<<"x^"<<curr->exp<<endl;
        curr=curr->next;
    }
}
int main()
{
    list lis;
    lis.display();
    return 0;
}
[
 本帖最后由 lyj123 于 2012-12-2 06:37 编辑 ]