gpt4 book ai didi

c++ - C++中的链表

转载 作者:太空狗 更新时间:2023-10-29 21:00:05 25 4
gpt4 key购买 nike

我使用类创建了一个简单的链表。在我的类中,我有 3 个方法:push_back()push_front() 和 print() 来打印list.push_front() 中的指针 p 有一些问题。用vs 2013调试时,p的valuenext是“unable to read memory”,我无法理解,所以请为我解释。

#include <stdio.h>
#include <iostream>
using namespace std;
class Note
{
public :
int value;
Note *next;
public :
Note(int value)
{
this->value = value;
this->next = NULL;
}
Note(int value,Note *next)
{
this->value = value;
this->next = next;
}
};

class LinkList
{
public :
Note *head;
public :
LinkList()
{
head = NULL;
}

void Push_back(int value)
{
Note *p = NULL;
if (head == NULL)
{
head = new Note(value, NULL);
}
else
{
p = head;
while (p->next != NULL)
p = p->next;
p->next = new Note(value, NULL);
}
}

void Push_front(int value)
{
Note *p = NULL;

p->value = 3;
p->next = this->head;
}

void print()
{
Note *p = NULL;
p = head;
while (p != NULL)
{
cout << p->value<<endl;
p = p->next;
}
}

int main()
{
LinkList test;
test.Push_back(6);
test.Push_back(5);
test.Push_back(12);
test.Push_front(13);
test.print();


}

最佳答案

您还没有为 p 分配任何内存以指向:

void Push_front(int value)
{
Note *p = NULL;
^^^^^^^^

// you are missing an allocation of a Note object:
// p = new Note;

p->value = 3;
p->next = this->head;
}

关于c++ - C++中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23098562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com