【发布时间】:2014-02-20 16:48:33
【问题描述】:
我正在尝试使用链表实现一个堆栈类,这是我的 stack.h
// File: Stack.h
#ifndef STACK_H
#define STACK_H
class Stack
{
private:
struct linklst{
int num;
int* next;
};
linklst* top;
public:
Stack();
~Stack();
void push(int i);
int pop();
bool isempty();
};
#endif
还有我的堆栈 .cpp
// Stack.cpp
#include"Stack.h"
using namespace std;
Stack::Stack(){
top = new linklst();
top->num = -1;
top->next = nullptr;
};
Stack::~Stack() {
linklst * r = new linklst();
while (true)
{
r = top;
top = top->next;
delete r;
}
delete top;
};
void Stack::push(int i){
linklst * r = new linklst();
r->num = i;
r->next = top;
top = r;
};
int Stack::pop(){
if (!isempty){
linklst * r = top;
top = top->next;
int x = r->num;
delete r;
return x;
}
};
bool Stack::isempty(){
return (top->next == nullptr);
};
每当我尝试将 top 分配给 r 时,我的问题就在 cpp 文件中,例如在 push 函数中 r->next = top; 我收到此错误“无法将 stack::linllst * 类型的值分配给 int * 类型的实体”
有谁知道我做错了什么??
任何帮助将不胜感激 谢谢
【问题讨论】:
-
不应该
int* next;是linklst* next;吗?链表中的节点应该指向下一个节点,而不是下一个节点包含的数据。
标签: c++ pointers linked-list stack