【发布时间】:2017-03-28 20:47:56
【问题描述】:
我正在为学校开发一个实验室,但我被困在一个双向链表的函数上。当我尝试使用 removeFront() 函数从列表中删除前端节点时,它返回 NULL 和 couts 让我创建一个列表,即使已经有一个列表。我将在下面发布我的 cpp 文件和 main,希望有人可以帮助我了解它出了什么问题。
//DLinkedList.h
#pragma once
#include <string>
using namespace std;
typedef string Elem;
struct DNode
{
Elem value;
DNode* next;
DNode* prev;
};
class DLinkedList
{
public:
DLinkedList() { header_ = NULL; }
~DLinkedList() { };
bool empty() const;
const Elem& front() const;
const Elem& back() const;
void addFront(const Elem& e);
void addBack(const Elem& e);
void removeFront();
void removeBack();
private:
DNode* header_;
DNode* trailer_;
protected:
void add(DNode* v, const DNode& e);
void remove(DNode* v);
};
//DLinkedList.cpp
#include <iostream>
#include "DLinkedList.h"
using namespace std;
const Elem& DLinkedList::front() const
{
if (header_ == NULL)
{
cout << "Please create a doubly linked list first.\n\n";
}
else
{
return header_->value;
}
}
void DLinkedList::addFront(const Elem& e) //DONE
{
// If there is no header
// create a temporary node and set
// the header to it
if (header_ == NULL)
{
DNode *temp;
temp = new(struct DNode);
temp->prev = NULL;
temp->value = e;
temp->next = NULL;
header_ = temp;
trailer_ = temp;
}
else
{
//Create current node to point to header
// and temp node to be the new front node
DNode *current;
DNode *temp;
current = header_;
temp = new(struct DNode);
temp->prev = NULL;
temp->value = e;
temp->next = current->next;
header_->prev = temp->next;
header_ = temp;
}
cout << "Element Inserted at the front." << endl;
}
void DLinkedList::removeFront()
{
// Check to see if there is anything
// in the list first
if (header_ == NULL)
{
cout << "Create a doubly linked list first.";
}
// Check to see if the list has more than one item.
// If it only has one node erase it.
DNode *current;
current = header_;
if (current->next == NULL)
{
header_->next = NULL;
header_->value = "";
header_->prev = NULL;
header_ = NULL;
}
else
{
current = current->next;
//header_->next = NULL;
//header_->value = "";
//header_->prev = NULL;
header_ = current;
header_->prev = NULL;
}
}
//Main.cpp
#include <iostream>
#include <string>
#include <cassert>
#include "DLinkedList.h"
using namespace std;
int main()
{
DLinkedList album;
album.addFront("Word");
album.addFront("Turn");
album.addFront("Bird");
album.addFront("Weird");
cout << album.front() << endl;
album.removeFront();
cout << album.front() << endl;
system("pause");
return 0;
}
【问题讨论】:
-
这样更好吗?
标签: c++ function doubly-linked-list