开发者

Single linked lists C++

Hey guys, I'm studying for a midterm right now and am working on trying to create a si开发者_StackOverflow中文版mple program using single linked list. All I want it to do is insert "1", "2", "3", "4" into the list and print it out. Please take a look at the following code:

#include <iostream>
#include <string>
using namespace std;

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};   

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout << p->data << " ";
        p = p->next;
    }
    cout << p->data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers. Can anyone tell me why?

Thanks so much!


There is a bug in the node constructor. The argument data conflicts with the memeber variable named data. This should fix it:

node::node(int data){
    this->data = data;
    next = NULL;
}

The better option is to rename the argument to something else. Also consider using an initialization list:

node::node(int d) : data(d), next(NULL) { }


node::node(int data) {
    data = data;
    next = NULL;
}

The line data = data is a problem for you. Rename the parameter to be different from the member. This ought to give you a series of garbage values (not pointers) for the member variable data.

Note: this is one of the reasons for naming convention distinguishing members variables, being it traling or leading _, m_ or wherever the balance is b/w info and aesthetics.


Well, I think both instances of data in

data = data;

are local; so the data member of node never gets anything assigned to it. What's getting printed are undefined values, not addresses. That's in any case stylistically terrible; there are many conventions here but a good one is _data for the class member, and data for the function argument. Make that simple change and see if that doesn't clear up your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜