无法实现链接列表

时间:2011-06-06 17:15:52

标签: c++ linked-list

我正在尝试实现一个简单的链接列表。初始值已成功插入,但未正确输入下一个元素。请帮我解决错误。谢谢。

#include<iostream>

using std::cout;

class node
{
    public:
        node():next(0){}
        void setNext(node *next){ next = next; }
        node* getNext(){ return next; }
        void setValue(int val){ value = val; }
        int getValue(){ return value; }

    private:
        int value;
        node *next;
};

class list
{
    public:
        list():head(new node()),len(0){}
        bool insert(int value);
        //bool remove(int value);
        int valueAt(int index);
        int length();

    private:
        node *head;
        int len;

};

bool list::insert(int value)
{
    node *current = 0;
    node *previous = 0;
    node *temp = 0;

    temp = new node();
    temp->setValue(value);

    current = head;
    previous = head;

    while((temp->getValue())>(current->getValue()))
    {
        previous = current;
        current = current->getNext();

        if(!current)
        {
            break;
        }
    }

    if(current == head)
    {
        temp->setNext(current);
        head = temp;

        len++;
    }
    else
    {
        temp->setNext(current);
        previous->setNext(temp);

        len++;
    }
}

int list::valueAt(int index)
{
    if((index < len) && (index >= 0))
    {
        node *current = 0;
        current = head;
        int count = 0;

        while(count < index)
        {
            current = current->getNext();
            count++;
        }

        return (current->getValue());
    }
    else
    {
        return -1;
    }
}


int main()
{
    list myList;

    myList.insert(5);
    myList.insert(20);
    myList.insert(10);

    cout<<"Value at index 1 : "<<myList.valueAt(1);

    return 0;
}

1 个答案:

答案 0 :(得分:3)

粗略地看了一眼后,问题可能是

void setNext(node *next){ next = next; }

您正在为自己分配一个变量,因为局部变量会掩盖实例变量。尝试将其更改为

void setNext(node *next){ this->next = next; }

在其他说明中:

  1. list::list中,您可能不应将head初始化为new node。这意味着您的链接列表在创建时将有一个任意节点,但长度为0.您应该考虑将head设置为NULL

  2. 在创作时,node有一个随机value。考虑在构造函数中要求参数,或者使用适当的默认值。

  3. -1list::valueAt的错误“无效值”,因为它也是要存储的节点的有效值。

  4. 您可能应该将list类重命名为slist,以表明它按排序顺序存储值。

相关问题