Stack - Push 'n Pop

Hey guys! I was trying to make Stack's push and pop functions. My push() is working fine but my pop() is giving me a headache. It doesn't delete the very last element entered in to the stack, where that might be!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <conio.h>
using namespace std;

class stack
{
	private:
		enum { MAX = 10 };
		int st [MAX];
		int top;
	public:
		stack() : top(-1)
		{}
		
		void push(int x)
		{ st[++top] = x; }
		
		void pop(int y)
		{ y = st[top];
		top--; }
		
		void output()
		{
			for(int x = 0; x<MAX; x++)
			{
				cout<<st[x]<<"  ";
			}
		}
};

int main()
{
	stack s1;
	int y;
	s1.push(78);
	s1.push(67);
	s1.pop(y);	
	s1.pop(y);
	s1.push(45);
	s1.pop(y);
	s1.push(23);
	s1.pop(y);
	s1.output();
	_getch();
	return 0;
	
}


According to my code here, pop() should have deleted 23 too! But it doesn't! And I can't make a teeny bit a sense of it! Please help! Thanks in advance!

And oh! Is there a way, the PC recognizes the variable contains garbage value and doesn't display it?! Just wondering!
Your output function doesn't care how many elements your stack contain. It uses MAX which is always 10.
That shouldn't stop my pop() function from moving the last occupied index to y, should it? :/
y inside the pop function is a copy of the variable that you passed to the function in main. Making changes to the copy will not affect the original object.

You can make it work by passing the argument by reference. You only need change line 15.
 
void pop(int& y)


Another way is to return the popped value as a function return value. Personally I prefer this way.
1
2
3
4
5
6
int pop()
{
	int y = st[top];
	top--;
	return y;
}
 
y = s1.pop();
Last edited on
Topic archived. No new replies allowed.