gpt4 book ai didi

C++堆栈实现弹出功能不起作用

转载 作者:行者123 更新时间:2023-11-30 01:41:08 24 4
gpt4 key购买 nike

我正在实现一个带有链接列表的堆栈以供审查。我的弹出功能无法正常工作。我用 main 中的节点创建了一个测试,它做的事情与我的 linkedList 函数所做的完全相同,但我每次都遇到段错误。这是代码。

#include <iostream>

struct Node{
int data;
Node* next;
};

class Stack{
private:
Node head;
int size;
public:
Stack();
~Stack();
int getSize();
void push(int val);
int pop();
void printStack();
};

Stack::Stack(){
head.data = 0;
head.next = NULL;
}

Stack::~Stack(){
}

int Stack::getSize(){
return size;
}

void Stack::push(int val){
Node newNode;
newNode.data = val;
if(size == 0) newNode.next = NULL;
else newNode.next = head.next;
head.next = &newNode;
size++;
}

int Stack::pop(){
int returnVal = head.next->data;
head.next = head.next->next;
return returnVal;
}
}


int main(){
Stack s;
s.push(8);
s.push(30);
s.push(40);
int value = s.pop();
int value2 = s.pop(); //segmentation fault
std::cout<<value<<"\n"<<value2<<"\n";


/* This works correctly
Node head;
head.data = 0;
head.next = NULL;
Node n1;
n1.data = 5;
n1.next = NULL;
head.next = &n1;
Node n2;
n2.data = 8;
n2.next = head.next;
head.next = &n2;
Node n3;
n3.data = 30;
n3.next = head.next;
head.next = &n3;

int value = head.next->data;
std::cout << value << "\n";
head.next = head.next->next;
value = head.next->data;
std::cout << value << "\n";
*/
return 1;
}

最佳答案

问题在于您如何创建节点。在你的例子中,你创建了一个局部变量,它只存在于函数 push() 的范围内。你可以使用这样的东西。

void Stack::push(int val){
Node* newNode = new Node;
newNode->data = val;
/* ... */
}

编辑:添加了堆栈的一个版本(绝不是完整的)

#include <iostream>

struct Node{
int data;
Node* next;
};

class Stack {
private:
Node* head;
int size;

public:
Stack();
~Stack();
int getSize();
void push(int val);
int pop();
void printStack();
};

Stack::Stack() : head(0), size(0)
{
}

Stack::~Stack(){
}

int Stack::getSize(){
return size;
}

void Stack::push(int val){
Node* newNode = new Node;
newNode->data = val;
newNode->next = head;

head = newNode;
size++;
}

int Stack::pop(){
if(head != 0)
{
int val = head->data;

Node* tmp = head;
head = head->next;

tmp->next = NULL;
delete tmp;

size--;

return val;
}
else
{
return -1; // what happens if stack is empty ?
}
}

关于C++堆栈实现弹出功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com