简体   繁体   中英

linked list implementation

Here is simple linked list code:

#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;
}

But it is giving me unexpected results. It prints 88 88 50 50 34 34 22 22 instead of (88,1.23) (50,2.34) (34,3.99) (22,2.99)

You're printing out data twice:

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

Presumably you wanted to print out data and ddata :

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

The error might have been easier to spot if the data members had more distinctive names.

void diplay(){

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

             }

Replace the display function with this code. (Instead of printing data and ddata you printed data twice)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM