无法分配给链表中的对象

Can't assign to object in linked list

本文关键字:对象 链表 分配      更新时间:2023-10-16

头部和尾部正在填充,并打印出值,但由于某种原因nodePtr保持空。当我在VS2015中调试时,头和尾号被填充,而字段保持为空

这是Linked_List

#ifndef _LINKED_LIST_
#define _LINKED_LIST_
#include <iostream>
class LinkedList
{
public:
struct Node
{
int number;
Node * next;
Node() : number(NULL), next(NULL) {};
Node(int number_, Node * next_ = NULL)
{
number = number_;
next = next_;
}
}*head, *tail, *nodePtr;

LinkedList();
~LinkedList();
void add(int num);
friend std::ostream& operator<<(std::ostream& out, LinkedList& list);
private:
int size;
};
#endif // _LINKED_LIST_

实现文件

include "linkedlist.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList() : head(NULL), tail(NULL), nodePtr(NULL) 
{
nodePtr = new Node();
}
LinkedList::~LinkedList()
{
Node * curr, *temp;
curr = head;
temp = head;
while (curr != NULL)
{
curr = curr->next;
delete temp;
temp = curr;
}
}

void LinkedList::add(int num)
{
Node * newNode = new Node();
newNode->number = num;
cout << newNode->number;
if (head == NULL)
{
head = newNode;
tail = newNode;
size++;
}
else
{
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
size++;
}
//cout << nodePtr->number; //empty, or some random
//just some tests
cout << head->number;
if (head->next != NULL)
{
cout << head->next->number;
}
cout << tail->number;
cout << endl;
}
std::ostream & operator<<(std::ostream & out, LinkedList & list)
{
out << list.nodePtr->number << endl;
return out;
}

主.cpp

#include <iostream>
#include "linkedlist.h"
using namespace std;
int main()
{
int num;
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
cout << list;

cout << "Press 1: ";
cin >> num;
return 0;
}

你在这里错过了一个基本概念。nodePtr不是什么神奇的节点,它知道所有其他节点,或者知道链表,或者可以用来打印它们的所有数字。

执行此操作时:

out << list.nodePtr->number << endl;

您所做的只是输出分配新Node并在nodePtr中存储指针时初始化的值:

nodePtr = new Node();

这调用了Node的默认构造函数,该构造函数将nodePtr->number设置为零。 (旁注,您将其初始化为NULL,而不是0- 您不应该将整数类型与指针类型混合使用,因此请将其更改为将值初始化为 0)。

它的值保持为 0,因为您从不修改它。nodePtr总是指向那个节点,因为你从来没有修改过nodePtr

您真正想做的是打印出您的列表。 让我建议一种正常的方法来做到这一点,从head开始并遵循节点链接:

std::ostream & operator<<(std::ostream & out, const LinkedList & list)
{
for( Node *node = list.head; node != nullptr; node = node->next )
{
out << node->number << std::endl;
}
return out;
}

最后,我建议你从课堂上完全删除nodePtr

你只在构造函数中使用nodePtr,你永远不会改变它的值。