我创建了一个链接列表,当我添加到列表的前面或后面时,它可以正常工作。我打印出来,一切都很好看。然后我从列表的前面(pop_front)中删除,由于某种原因,行temp = head->getPrevious();
(List.cpp)返回值0x000000,所以很明显它实际上并没有获得指向前一个节点的指针。我已经介入它,我看不到任何东西。任何帮助都会很棒!
Main.cpp的
#include "stdafx.h"
#include "List.h"
int main()
{
List partsList;
partsList.push_front(22);
partsList.push_front(25);
partsList.push_front(32);
partsList.push_back(100);
partsList.display();
cout << "now we are going to remove the first item in the list" << endl;
system("PAUSE");
partsList.pop_front();
partsList.display();
system("PAUSE");
cout << "now we are going to remove the LAST item from the list" << endl;
partsList.pop_back();
partsList.display();
system("PAUSE");
return 0;
}
List.h
#pragma once
#include "node.h"
#include <iostream>
using namespace std;
class List
{
private:
int listSize;
Node* n;
Node* temp;
Node* head;
Node* tail;
public:
List();
void push_front(int);
void push_back(int);
void pop_front();
void pop_back();
void display();
~List();
};
List.cpp
#include "stdafx.h"
#include "List.h"
List::List()
{
}
void List::push_front(int dat)
{
if (listSize == 0) {
n = new Node;
n->setData(dat);
listSize++;
temp = n;
head = n;
tail = n;
}
else {
n = new Node;
n->setData(dat);
listSize++;
temp = head;
head = n;
n->setNext(temp);
n->setPrevious(nullptr);
temp->setPrevious(n);
temp = n;
}
}
void List::push_back(int dat)
{
if (listSize == 0) {
n = new Node;
n->setData(dat);
listSize++;
temp = n;
head = n;
tail = n;
}
else {
n = new Node;
n->setData(dat);
listSize++;
temp = tail;
temp->setNext(n);
n->setPrevious(temp);
// SET NEXT TO NULL
temp = n;
tail = temp;
}
}
void List::pop_front()
{
temp = head->getPrevious();
delete head;
head = temp;
listSize--;
}
void List::pop_back()
{
temp = tail->getPrevious();
delete tail;
tail = temp;
tail->setNext(nullptr);
listSize--;
}
void List::display()
{
Node* test = head;
for (int i = 0; i < listSize; i++) {
cout << test->getData() << endl;
test = test->getNext();
}
}
List::~List()
{
}
Node.h
#pragma once
class Node
{
private:
int data;
Node* next;
Node* previous;
public:
Node();
int getData();
void setData(int);
void setNext(Node*);
void setPrevious(Node*);
Node* getPrevious();
Node* getNext();
~Node();
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node()
{
}
int Node::getData()
{
return data;
}
void Node::setData(int dat)
{
data = dat;
}
void Node::setNext(Node* nextNode)
{
next = nextNode;
}
void Node::setPrevious(Node* prev)
{
previous = prev;
}
Node * Node::getPrevious()
{
return previous;
}
Node * Node::getNext()
{
return next;
}
Node::~Node()
{
}
答案 0 :(得分:3)
在head->getPrevious();
中,您正在调用nullptr
,显然正在返回getNext()
,并将其设置为列表的新头。它应该是{{1}}。
顺便说一句:你不应该在List对象中存储n和temp等临时变量。在操作方法之外不需要它们,只会使对象膨胀。