链表实现

时间:2011-10-09 09:29:57

标签: c++ linked-list

这是简单的链表代码:

#include <iostream>
using namespace std;
class link
{
    public:
    int data;
    double ddata;
    link *next;
    link(int id,double dd){
        data=id;
        ddata=dd;
    }

    void diplay(){
        cout<<data<<" ";
        cout<<data<<" ";

    }
};

class linkedlist{
    private :
        link *first;
    public:
        linkedlist(){
            first=NULL;
        }

        bool empthy(){
            return (first==NULL);
        }

        void insertfirst(int id,double dd){
            link *newlink=new link(id,dd);
            newlink->next=first;
            first=newlink;
        }

        link* deletefirst(){
            link *temp=first;
            first=first->next;
            return temp;
        }

        void display(){
            cout<<" (list ( first -> last ) )   ";
            link *current=first;
            while(current!=NULL){
                current->diplay();
                current=current->next;
            }
            cout<<endl;
        }
};

int main(){
    linkedlist *ll=new linkedlist();
    ll->insertfirst(22,2.99);
    ll->insertfirst(34,3.99);
    ll->insertfirst(50,2.34);
    ll->insertfirst(88,1.23);
    ll->display();
    return 0;
}

但它给了我意想不到的结果。它打印88 88 50 50 34 34 22 22而不是(88,1.23)(50,2.34)(34,3.99)(22,2.99)

2 个答案:

答案 0 :(得分:1)

您打印data两次:

        cout<<data<<" ";
        cout<<data<<" ";

据推测,您想要打印dataddata

        cout<<data<<" ";
        cout<<ddata<<" ";

如果数据成员具有更多不同的名称,则可能更容易发现错误。

答案 1 :(得分:1)

void diplay(){

             cout<<data<<" ";
             cout<<ddata<<" ";

             }

用此代码替换display函数。 (而不是打印dataddata两次打印数据)