【发布时间】:2019-06-22 02:41:14
【问题描述】:
我正在制作一个基于指针的堆栈模板。
Push 方法工作得很好,但我的 pop 方法似乎不起作用。有人能看出这里有什么问题吗?在 gdb 中,我展示了第二个 while 循环导致分段错误。怎么了?
代码如下:
#include <iostream>
#include <string>
using namespace std;
template <typename k>
class stack;
template <typename k>
class node{
private:
friend class stack<k>;
k data;
node<k> *next;
public:
node(k _x): data(_x), next(NULL) {}
};
template <typename k>
class stack{
private:
node<k> *start;
unsigned int i;
public:
stack(): start(NULL), i(0) {}
~stack(){
while(i!=0) pop();
}
void push(k element){
node<k> *ptr;
node<k> *temp;
ptr=new node<k>(element);
if(start==NULL){
start=ptr;
ptr->next==NULL;
}
else{
while(temp->next!=NULL) temp=temp->next;
temp->next=ptr;
ptr->next=NULL;
}
i++;
}
int pop(){
if(i==1){
int item=start->data;
start=NULL;
i=0;
return item;
}
else{
node<k> *temp=start; //k is my typenam in templates
node<k> *top=start;
while(temp->next!=NULL) temp=temp->next; //getting to last element
while(top->next!=temp) top=top->next; //getting to element before the last
top->next=NULL; //setting next to NULL
int item=temp->data; //getting data from element popped
delete(temp); //deleting last node
i--; //decreasing the size
return item; //returning popped element
}
}
bool isempty(){
if(i==0) return 1;
else return 0;
}
int rozmiar(){
return i;
}
};
int main()
{
stack<char> s;
string slowo;
cin>>slowo;
for(int i=0; i<slowo.length(); i++){
s.push(slowo[i]);
}
for(int i=0; i<slowo.length(); i++){
s.pop();
}
return 0;
}
在 main 中有一个测试,输入单词,将单个字母压入堆栈,然后使用 pop 反向读取。 编辑。添加完整代码。
【问题讨论】:
-
你的
for循环中有一个有符号和无符号的比较 -
为什么不
k pop()和k item = temp->data? -
这不是用链表实现栈吗?在这种情况下,您可以使用此链接来帮助指导您。 geeksforgeeks.org/implement-a-stack-using-singly-linked-list
-
@TrebuchetMS 是的,错过了。谢谢!