c++ - 双向链表函数c++(作业)
问题描述
我的教授给了我们下面的代码来修改,它从一个链表开始,并告诉我们做一个双向链表。我的displayLast()
函数仅以与 相同的顺序显示display()
,虽然该addEnd()
函数没有给出错误,但它在尝试显示值时会出现。我想让'displayLast()'反向显示,然后希望我能自己弄清楚最后的添加。
/*******************************
* Week 2 lesson: *
* a simple LinkedList class *
*******************************/
#include <iostream>
#include "LinkedList.h"
using namespace std;
/*
* Initializes the list to empty creating a dummy header node.
*/
LinkedList::LinkedList()
{
first = new Node;
first->next = NULL;
}
/*
* Destructor. Deallocates all the nodes of the linked list,
* including the header node.
*/
LinkedList::~LinkedList()
{
Node *temp;
while (first != NULL)
{
temp = first;
first = first->next;
delete temp;
}
}
/*
* Determines whether the list is empty.
*
* Returns true if the list is empty, false otherwise.
*/
bool LinkedList::isEmpty()
{
return first->next == NULL;
}
/*
* Prints the list elements.
*/
void LinkedList::display()
{
Node * current = first->next;
while (current != NULL)
{
cout << current->info << " ";
current = current->next;
}
cout << endl;
}
void LinkedList::displayLast()
{
Node *current = last;
while (current != NULL)
{
cout << current->info << " ";
current = current->prev;
}
cout << endl;
}
/*
* Adds the element x to the beginning of the list.
*
* x: element to be added to the list.
*/
void LinkedList::add(int x)
{
Node *p = new Node;
p->info = x;
p->next = first->next;
p->prev = last;
first->next = p;
last = p;
}
void LinkedList::addEnd(int x)
{
Node *p = new Node;
p->info = x;
p->prev = last;
last->next = p;
last = p;
}
/*
* Removes the first occurrence of x from the list. If x is not found,
* the list remains unchanged.
*
* x: element to be removed from the list.
*/
void LinkedList::remove(int x)
{
Node * old = first->next,
*p = first;
//Finding the address of the node before the one to be deleted
bool found = false;
while (old != NULL && !found)
{
if (old->info == x) found = true;
else
{
p = old;
old = p->next;
}
}
//if x is in the list, remove it.
if (found)
{
p->next = old->next;
delete old;
}
}
这里是 。文件:
class LinkedList
{
public:
LinkedList();
~LinkedList();
bool isEmpty();
void display();
void add(int);
void remove(int);
void addEnd(int);
void displayLast();
private:
Node * first; //pointer to header (dummy) node
Node *last;
};
解决方案
推荐阅读
- ruby-on-rails - 如何在 Rails 6 中的 ruby gem 中存在 jQuery 代码
- c# - 使用循环统一 c# 实例化后如何将唯一变量设置为预制件?
- javascript - 用于图表的 React UseEffect 数据数组
- ios - 来自“[任何]?”的演员表 到不相关的类型“SpotlightView”总是失败
- ios - 如何根据测验结果对单元格进行排序?
- javascript - 反应错误:渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null
- python - 如何检查机器人连接的语音通道 ID?(discord.py)
- javascript - Django 模板 - 列表未正确呈现
- node-red - 有没有办法选择在 NodeRED 服务器中创建的类别?
- ios - 验证后无法直接登录,但第二次点击成功