Please help: C++ Stack Implementation Code

I need to write the code for getLength, isEmpty, and peek. I am unsure of what to write since I have never done this before.

Also, I need to write a loop in main that takes in an unknown number of positive integers, and pushes them onto the stack.

I am completely new to c++, so any help would be greatly appreciated.

#include <iostream>
using namespace std;

class Stack_int
{
private:
// Structure for the stack nodes
struct StackNode {
int value; // Value in the node
StackNode *next; // Pointer to next node
};

StackNode *top; // Pointer to the stack top
int length;

public:
Stack_int(){ top = NULL; length = 0; } //Constructor
//~Stack_int(); // Destructor

// Stack operations
bool isEmpty() {}
bool push(int);
// int pop();
int peek() {}
int getLength() {}
};

/**~*~*
Member function push: pushes the argument onto the stack.
*~**/
bool Stack_int::push(int item)
{
StackNode *newNode; // Pointer to a new node

// Allocate a new node and store num there.
newNode = new StackNode;
if (!newNode)
return false;
newNode->value = item;

// Update links and counter
newNode->next = top;
top = newNode;
length++;

return true;
}


int main() {

Stack_int s;
int item;


return 0;
}
For getLength function just return length.
For isEmpty return if length == 0
For peek return the value of top.

To read the integers.
1
2
3
int num;
while (cin >> num)
  // add num to the stack. Input ends when you hit Ctrl+Z + return 


Do you do course or follow a book?
Thank you! Would something like this be correct?

bool isEmpty() {
if (length == 0)
return true;
else
return false;
}

int peek() {
return top;
}

int getLength() {
return length;
}

Also, I am sorry but how would you add num to stack?

I am trying to learn myself.
Last edited on
1
2
3
4
5
6
bool isEmpty() {
if (length == 0)
return true;
else
return false;
}

It's correct but easier to write is: return length == 0;

1
2
3
int peek() {
return top;
}

That's not correct. top is struct StackNode, but what you want is an int.
You need to return top.value;

Also, I am sorry but how would you add num to stack?

The stack class has a fuction push.

Where did you get this stack class?
Why don't you use the std::stack? http://www.cplusplus.com/reference/stack/stack/
Topic archived. No new replies allowed.