简体   繁体   English

链表实现

[英]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) 它打印88 88 50 50 34 34 22 22而不是(88,1.23)(50,2.34)(34,3.99)(22,2.99)

You're printing out data twice: 您要打印两次data

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

Presumably you wanted to print out data and ddata : 想必你想打印出dataddata

        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. 用此代码替换display功能。 (Instead of printing data and ddata you printed data twice) (除了打印dataddata你打印数据两次)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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