c++ - 无法在我的链接列表中插入项目,头部始终为 NULL

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

我是 C++ 的新手,正在尝试创建一个包含整数值的单链表数据结构。

我的插入方法有问题,似乎我传递给函数的头引用总是 NULL(也许我错误地传递了它的值)。

我想使用下面的插入方法:

insert(L,x):其中 L 是指向列表第一个元素的指针,x 是要插入的整数值。

这是我的链表hpp文件:

class LinkedList{

private:
 struct Node{
    int data;
    Node* next;
 };
 Node* head;

public:
 LinkedList();
 ~LinkedList();

 void insert(Node* _head,int _value);
 int lenght(Node* _head);
 Node* getHead();
};

这是我的链表cpp文件:

LinkedList::LinkedList(){
 head = NULL;
}

LinkedList::~LinkedList(){

}

void LinkedList::insert(LinkedList::Node* _head,int _value){
 Node* temp = new Node;
 temp->data = _value;
 temp->next = NULL;

 // _head is NULL every time this function is called

 if(_head == NULL){
    _head = temp;
 }
 else{
    while(_head->next != NULL){
        _head = _head->next;
    }
    _head->next = temp;
 }
}

int LinkedList::lenght(LinkedList::Node* _head){
 int count = 0;

 while(_head!=NULL){
    count++;
    _head=_head->next;
 }
 return count;
}


LinkedList::Node* LinkedList::getHead(){
 return head;
}

这是主文件:

int main(int argc, const char * argv[]) {

 LinkedList list;

 list.insert(list.getHead(), 3);
 list.insert(list.getHead(), 4);
 list.insert(list.getHead(), 5);
 list.insert(list.getHead(), 6);

 cout << list.lenght(list.getHead()); //This prints out 0 elements 

 return 0;
}

代码运行正常,但列表中的元素数始终为 0。 插入函数中的 _head 似乎总是指向 null。

我希望我能很好地描述问题,感谢您的提前帮助。

安德里亚

最佳答案

头节点始终等于 nullptr,因为函数 insert 处理函数 getHead 返回的原始头的拷贝。所以改变拷贝不会影响原来head的值。

这些成员函数

void insert(Node* _head,int _value);

Node* getHead();

没有意义。为什么私有(private)数据成员头部返回给列表的用户?在这种情况下,用户可以绕过公共(public)界面直接更改列表中的数据。

像这样声明函数insert

void insert( int value );

并完全删除函数 getHead

在这种情况下,函数insert(考虑到所使用的算法,最好重命名为append)

void LinkedList::insert( int value )
{
    Node *temp = new Node { value, nullptr };

    Node **tail = &head;

    while ( *tail ) tail = &( *tail )->next;

    *tail = temp;
} 

在 main 中,函数可以这样调用

list.insert( 3 );
list.insert( 4 );
list.insert( 5 );
list.insert( 6 );

如果赋值要求有 getHead 函数,那么至少像 delare 函数一样

Node * & getHead();

在这种情况下,函数插入看起来像

void LinkedList::insert( Node * &node, int value )
{
    Node *temp = new Node { value, nullptr };

    Node **tail = &node;

    while ( *tail ) tail = &( *tail )->next;

    *tail = temp;
} 

关于c++ - 无法在我的链接列表中插入项目,头部始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58521247/

相关文章:

生成随机数字字符串的算法,长度为 10,000 个字符?

c++ - 用 std::set 替换 std::map 并按索引搜索

任何信号上的 C++ 轮询错误

algorithm - Google Trends的系统设计?

c++ - 程序中变量的基址/静态地址是什么?

c++ - 不同的函数指针是否相互兼容?

c++ - 为什么语句int null = 0, *p = null 是非法的?

c++ - protected 析构函数和对象初始化

c++ - 查找 vector 中变量之间的百分比差异 C++

保留访问有限许可的算法