我正在尝试使用双向链表实现堆栈。我知道我的堆栈类(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()
的调用?非常感谢任何帮助或建议!
答案 0 :(得分:0)
您可以创建堆栈类,然后使用链接列表作为其容器。在链表类中,对项目数量几乎没有限制,因此您添加了人工限制以使其像堆栈一样工作。在链表中,可以在列表中的任何位置添加/删除项目,您可以限制添加/删除尾节点,使其像堆栈一样工作。以下示例演示了该用法。
节点这纯粹是一个编程练习。与双向链表相比,堆栈相对原始。在堆栈中封装链表没有任何优势。另请注意,为了简化问题,我将所有成员声明为.cache
,您可能希望将某些成员更改为public
/ protected
private