Я получаю ошибку сегментации - основной дамп во время выполнения. Я пытаюсь выяснить, как избавиться от ошибки сегментации. Это домашнее задание класса. EDIT: добавлены вход и выход ниже.
//client.cpp
#include <iostream>
#include "stack.h"
using namespace std;
int main(void){
stack unsorted;
stack stack1;
stack stack2;
stack stack3;
int const MAX_VALUES = 5;
int input;
cout << "Please input "<< MAX_VALUES << " unique integers.\n";
cout << "Click the ENTER key after each integer inputted." <<endl;
for (int i = 0; i < MAX_VALUES; i++)
{
cin >> input;
stack1.Push(input);
unsorted.Push(input);
}
cout << "Unsorted Stack: " <<endl;
for (int i = 0; i < MAX_VALUES; i++)
{
cout<<unsorted.Pop()<<endl;
}
cout << "Sorted Stack: "<<endl;
while((!stack1.IsEmpty())&&(!stack3.IsEmpty())){
if ((stack1.IsEmpty())&&(!stack3.IsEmpty()))
{
stack2.Push(stack3.Pop());
}
if (stack2.Top() > stack1.Top())
{
stack3.Push(stack2.Pop());
}
if (stack3.Top() < stack1.Top())
{
stack2.Push(stack3.Pop());
}
else
{
stack2.Push(stack1.Pop());
}
}
while (!stack2.IsEmpty()){
cout << stack2.Pop() << endl;
}
}
//stack.h
#include <cstddef>
struct node;
class stack
{
public:
stack();
~stack();
bool IsFull();
bool IsEmpty();
void Push(int input);
int Pop();
int Top();
private:
node* top;
int const MAX_VALUES = 5;
int count;
};
//stack.cpp
#include "stack.h"
struct node
{
int input;
node* next;
};
stack::stack()
{
top = NULL;
count = 0;
}
bool stack::IsFull()
{
if (MAX_VALUES > count)
{
return false;
}
return true;
}
bool stack::IsEmpty(){
if (top == NULL){
return true;
}
else{
return false;
}
}
void stack::Push(int num)
{
if(IsFull() == false)
{
node* newNode = new node;
newNode->input = num;
newNode->next = top;
top = newNode;
count ++;
}
}
int stack::Top()
{
int topval;
topval = top->input;
return topval;
}
int stack::Pop()
{
int Popped;
if (top != NULL)
{
node* temp = top;
top = top->next;
Popped = temp->input;
delete temp;
return Popped;
}
count--;
}
stack::~stack()
{
node* current = top;
while( top != NULL)
{
node* next = current->next;
delete current;
current = next;
}
top = NULL;
}
Вход: введите 5 уникальных целых чисел. Нажмите клавишу ENTER после ввода каждого целого числа. 7 1 56 67 8
Вывод:
Unsorted Stack: 8 67 56 1 7 Сортированный стек: ошибка сегментации (сбрасывание ядра)
Есть несколько проблем.
Во-первых, ваш Pop
:
int stack::Pop()
{
int Popped;
if (top != NULL)
{
node* temp = top;
top = top->next;
Popped = temp->input;
delete temp;
return Popped;
}
count--;
}
который уменьшает count
только тогда, когда стек пуст, но не возвращает ничего, если он есть.
Вам нужно что-то большее:
int stack::Pop()
{
int Popped = -1; // Make sure the return value is well-defined
if (!IsEmpty())
{
node* temp = top;
top = top->next;
Popped = temp->input;
delete temp;
count--; // Only decrement if we actually popped something.
}
return Popped;
}
и деструктор:
stack::~stack()
{
node* current = top;
while( top != NULL)
{
node* next = current->next;
delete current;
current = next;
}
top = NULL;
}
Цикл никогда не остановится, потому что у вас неправильное условие завершения - если стек не пуст, top
не станет NULL
.
Должен быть
stack::~stack()
{
node* current = top;
while (current != NULL)
{
node* next = current->next;
delete current;
current = next;
}
top = NULL;
}
И цикл в main
запускается следующим образом (я удалил некоторые ненужные круглые скобки):
while (!stack1.IsEmpty() && !stack3.IsEmpty()) {
if (stack1.IsEmpty() && !stack3.IsEmpty())
где, if
условие не будет истинным, если в while
условие - stack1
не может быть и пустым, и не пусто.
Сторона примечания: ограничение размера при реализации стека как связанного списка немного нечетное.