[英]Linked List in C++
我創建一個簡單的鏈接列表使用class.in我的類,我有3個方法是: push_back()
, push_front()
和print()打印列表。我在push_front()
指針p有一些問題。 當通過vs 2013進行調試時,p的value
和next
是“無法讀取內存”,我無法理解,所以請為我解釋。
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.