【发布时间】:2017-03-01 17:32:36
【问题描述】:
我正在尝试使用双向链表来实现堆栈。我知道我的堆栈类(push、pop)的函数应该包含对我的双向链表类的成员函数的调用,但我在实际实现它时遇到了麻烦。
dlist.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "dlist.hpp"
using namespace std;
void dlist::appendNodeFront(int shares, float pps){
Node *n = new Node(shares, pps);
if(front == NULL){
front = n;
back = n;
}
else {
front->prev = n;
n->next = front;
front = n;
}
}
void dlist::appendNodeBack(int shares, float pps){
Node *n = new Node(shares, pps);
if(back == NULL){
front = n;
back = n;
}
else {
back->next = n;
n->prev = back;
back = n;
}
}
void dlist::display(){
Node *temp = front;
cout << "List contents: ";
while(temp != NULL){
cout << temp->value << " ";
temp = temp->next;
}
cout << endl;
}
void dlist::display_reverse(){
Node *temp = back;
cout << "List contents in reverse: ";
while(temp != NULL){
cout << temp->value << " ";
temp = temp->prev;
}
cout << endl;
}
void dlist::destroyList(){
Node *T = back;
while(T != NULL){
Node *T2 = T;
T = T->prev;
delete T2;
}
front = NULL;
back = NULL;
}
stack.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "stack.hpp"
using namespace std;
stack::stack(){
int i;
for(i = 0; i < 1500; i++){
shares[i] = 0;
pps[i] = 0;
}
first = 0;
}
void stack::push(int num, float price){
if(first ==(1500-1)){
cout << "Stack is full" << endl;
return;
}
first++;
shares[first] = num;
pps[first] = price;
return;
}
void stack::pop(int *num, float *price){
if(first == -1){
cout << "Stack is empty" << endl;
return;
}
num = &shares[first];
price = &pps[first];
cout << shares[first] << endl;
cout << pps[first] << endl;
shares[first] = 0;
pps[first] = 0;
first--;
return;
}
堆栈中的推送函数应该基本上是对appendNodeFront()或appendNodeback()的调用吗?非常感谢任何帮助或建议!
【问题讨论】:
-
Push 应该在栈尾追加一个元素,所以 appendNodeback() 是正确调用的函数。对于弹出操作,您需要删除插入堆栈的最后一个元素,因此必须实现 removeLastNode() 函数。
-
似乎这些函数的职责是混合的。例如,创建节点并将其附加到某处。当您分离职责时,事情会变得更简单。嘿,这个概念甚至有its own Wikipedia page!哇哦。
-
两种场景:从头部推/从头部弹出或从尾部推/从尾部弹出。关键是最后插入的元素应该是删除的第一个元素(LIFO)。
-
为什么不使用
std::stack,或者至少使用std::list? -
堆栈不需要双向链表。单链表就足够了。列表的头部成为堆栈的顶部。如果你想要双链表,你选择哪一端并不重要——你只需要确保你
push()和pop()来自同一端。