Pushing and array based stack

Currently this is my assignment. I'm just wondering my code will work.

Create a class/struct.

Members:
MaxSize const = 10
Define an array that holds 10 items.
Count - indicates how many items are on the stack.

Methods:
Push
- Accepts a number and adds to the top of the stack.
- If the stack is full emit an error indicating full.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Stack::Push(int n)
{
	if(a[MaxSize - 1] == NULL)
	{
		for(int i = MaxSize - 1; i > 0 ; i--)
		{
			if(a[i] != NULL)
			{
				for(int j = i; j > 0 ; j--)
					a[j+1] = a[j];
				break;
			}
		}
		a[0] = n;
	}
	else
		cout << "Error, stack is full." << endl;
}
Last edited on
Only way to REALLY find out if your code is working is to run and test it ;)
And btw, that's not really the best way to implement a stack. You're moving each item up the stack (slow) when you're pushing, and what if a stack element is used, but holds NULL? Ideally you would be able to use a "stack pointer" which points to the next available slot (or the one last pushed to). This avoids you having to set each element to NULL each time you pop. Not sure what constraints your assignment has though, so it might not be doable.

Good luck though!
I ran it and the code doesn't push the numbers down when I want to add a number to the top of the stack. Also I dont know if I can use the stack pointer because my professor told me to make an array based stack.
The actual elements in the stack are at array[0], array[1], array[2], ..., array[count-1].
The element to be popped is the one at the top of the stack; the one at array[count-1]
The next element pushed will be placed at the top of the stack; at array[count].


To push an element on to the stack, we do not have to move any of existing elements.
Place the element at array[count], and then increment count.

To pop an element off the stack, decrement count and return the element that was just popped off
(that is, the element at array[count]).

spoiler: http://coliru.stacked-crooked.com/a/8ebab40b7aa947dc
Topic archived. No new replies allowed.