c++ - 单链表 C++ : Head pointer does not connect to next node

标签 c++ linked-list singly-linked-list

<分区>

对于我的作业,我必须创建一个单链表并插入 3 个项目。我尝试使用面向对象的方法,而不是我的老师和几乎所有人都使用的纯指针方法; head 和 tail 都是我的列表类的节点和属性。我的代码的唯一问题是头节点的指针不会更新到下一个节点。谁能帮我改正这个问题?

#include <iostream>
using namespace std;



class node
{
public:
    int element;
    node* ptr;
    friend class list;
};



class list
{
public:
    //Including head and tail attributes and making them public so that 
they are easily accessible to anyone using the linked list construction
    node head;
    node tail;

    list()
    {
        head.element = -1; //-1 is sentinel value
        tail.element = -1;
        head.ptr = NULL;
        tail.ptr = NULL;
        head = tail;
    }

    bool empty()
    {
        return((head.ptr == NULL) && (head.element == -1));
    }

    void insert(int a)
    {
        if(empty())
        {
            head.element = a;
            tail.element = a;
        }

        else
        {
            //Making a new unnamed node, inserting the new value, and 
updating the tail attribute
            node* v = new node;
            tail.ptr = v;
            v -> element = a;
            v -> ptr = NULL;
            tail.element = v-> element;
            tail.ptr = v -> ptr;
        }
    }

    void print()
    {
        int i = 0;
        node *pointer = head.ptr;
        while(pointer != NULL)
        {
            cout << "The " << i+1 << "th element is: " << pointer -> 
element;
            pointer = pointer -> ptr;
            i++;
        }
    }

};



int main()
{
    int values[3] = {1, 2, 3};
    list lst;
    for(int i = 0; i < 3; i++)
    {
        lst.insert(values[i]);
    }

    cout << lst.head.element << endl;
    cout << lst.tail.element;
    lst.print();

};

最佳答案

头节点和尾节点应保留为虚拟节点,而不是列表的一部分。头节点和尾节点的元素值不需要初始化或检查。非空列表的插入顺序是

        // ...
        v->ptr = head.ptr; 
        head.ptr = v;
        // ...

看看您是否可以修复其余代码。

如果创建追加函数,非空列表的追加序列是

        // ...
        v->ptr = NULL;
        tail.ptr->ptr = v;
        // ..

关于c++ - 单链表 C++ : Head pointer does not connect to next node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46613932/

相关文章:

c++ - 为什么Webkit运行时pow()计算错误?

c++ - glBufferData 之后需要glFlush 吗?

c - 链表的意外行为

c++ - 创建 C++ 类的新实例,结果重复

c - 链表产生警告的函数

c - 链表-插入新节点

c++ - 如何从 C 中的 pe (exe) 文件中删除一些数据

c++ - 是一个二叉树 BST 但只有右 child 才允许重复

java - 使用java删除链表中的节点

c - 访问冲突读取位置 0xCDCDCDCD