【问题标题】:trouble implementing a linked list实现链表的麻烦
【发布时间】:2011-06-06 17:15:51
【问题描述】:

我正在尝试实现一个简单的链接列表。初始值插入成功,但下一个元素没有正确输入。请帮我解决错误是什么。感谢赞赏。

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

【问题讨论】:

  • 这是作业吗?它确实看起来像。如果是这种情况,您应该这样标记您的问题。
  • @David 不要这么快就谴责这是作业,有些人只是喜欢练习,链表特别有趣。
  • 如果您的问题已解决,请接受答案

标签: c++ linked-list


【解决方案1】:

粗略一瞥,或许问题出在

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

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

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

在其他注释中:

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

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

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

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

【讨论】:

  • 天哪...我想我很愚蠢...感谢您指出这一点。非常感谢。
  • @Ramilla 你不傻,我以前也做过。也可能是我们都很愚蠢。
猜你喜欢
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
相关资源
最近更新 更多