I just implemented a stack using an array and am curious as to why people start their tops at -1. Is it more inefficient to start at 0? I have a programming assignment to implement a stack that performs basic functions, and tried doing it on my own first.
After I got it to work I looked around to see other implementations. Most people start their tops at -1. Is there a benefit to that? Is it wrong to start at 0?
here's my working code:
header file:
#ifndef H_Stack
#define H_Stack
#include <iostream>
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
class arrayStack
{
private:
int stackSize;
int stackTop;
int *stackArray;
public:
arrayStack(const int &x);
void push(const int &x);
bool is_full();
bool is_empty();
int size();
int top();
void pop();
~arrayStack();
};
class linkedStack
{
private:
nodeType *stackTop;
public:
linkedStack();
void push(const int &x);
int size();
int top();
void pop();
bool is_empty();
~linkedStack();
};
#endif
Imp file:
#include "stack.h"
#include <iostream>
#include <cassert>
using namespace std;
arrayStack::arrayStack(const int &x)
{
if (x <= 0)
{
stackSize = 20;
stackArray = new int[stackSize];
}
else
{
stackTop = 0;
stackSize = x;
stackArray = new int[stackSize];
}
}
bool arrayStack::is_full()
{
return (stackTop == stackSize);
}
void arrayStack::push(const int &x)
{
if (!is_full())
{
stackArray[stackTop] = x;
stackTop++;
}
}
bool arrayStack::is_empty()
{
return (stackTop == 0);
}
int arrayStack::size()
{
return stackSize;
}
int arrayStack::top()
{
assert(stackTop != 0);
return stackArray[stackTop - 1];
}
void arrayStack::pop()
{
if (!is_empty())
stackTop--;
else
{
cout << "can't pop from an empty stack.";
}
}
arrayStack::~arrayStack()
{
delete[] stackArray;
}
linkedStack::linkedStack()
{
stackTop = nullptr;
}
void linkedStack::push(const int &x)
{
nodeType *newNode;
newNode = new nodeType;
newNode->info = x;
newNode->link = stackTop;
stackTop = newNode;
}
int linkedStack::size()
{
int count = 0;
nodeType *temp;
temp = stackTop;
while (temp != nullptr)
{
temp = temp->link;
count++;
}
return count;
}
int linkedStack::top()
{
assert(stackTop != nullptr);
return stackTop->info;
}
void linkedStack::pop()
{
assert(!is_empty());
nodeType *temp = stackTop;
stackTop = stackTop->link;
delete temp;
}
bool linkedStack::is_empty()
{
return (stackTop == nullptr);
}
linkedStack::~linkedStack()
{
while (stackTop != nullptr)
{
pop();
}
}
it successfully pops/pushes. It is not circular so its not efficient or very useful... but I had to write it for school.
using namespace std;from your header file.topbe -1 can be an easy way of showing the stack is currently empty. leavingtopat index 0 can imply to some people that index 0 is being used. But again, this is all just programming methods. If you feel more comfortable leaving top at 0 and your stack works properly, more power to you.