Help with Stacks...

Hi guys, I am new to stacks and need help..

1) Why does this program not pop out the correct information. It should pop out "5 4 3 2 1"...

2)If anyone would be generous to help me convert this to a template.. That would be great as well..

Thanks in advance....

PROGRAM:

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
using namespace std;

class Stack	//This is a stack class
{
	public:
		Stack();
		int getTop();
		int pop();
		void push (int Element);
		int Empty();
		int CurrSize();
		int IsFull();
	private:
		int stack[50];
		int MaxCapacity;
		int top;
};

Stack :: Stack ()
{
	MaxCapacity = 50;
	top = -1;
}

int Stack :: getTop()
{
	if (!Empty())
	{
		return (stack[top]);
	}
}

int Stack :: pop ()
{
	if (!Empty())
	{
		return (stack[top]);
		top--;
	}
}

int Stack :: Empty()
{
	if (top == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int Stack :: IsFull()
{
	if (top == (MaxCapacity-1))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int Stack :: CurrSize ()
{
	return (top+1);
}

void Stack :: push (int Element)
{
	if (!IsFull())
	{
		top++;
		stack[top] = Element;
	}
}

int main()
{
	Stack test;
	int x;
	
	cout << "Enter 5 numbers" << endl << endl;
	
	for (int i = 0; i < 5; i++)
	{
		cin >> x;
		test.push(x);
	}
	
	for (int i = 0; i < 5; i++)
	{
		cout << test.pop();
	}
	
	return 0;
}

Last edited on
1)

1
2
3
4
5
6
7
8
int Stack :: pop ()
{
	if (!Empty())
	{
		return (stack[top]);
		top--;
	}
}


return exits the function. So your top-- line is never being executed.



2) I'll pass on this one. It's not really difficult to make it a template... just use a generic type 'T' instead of int for the values in the stack.
Nevermind. So I changed line 38 and 39 from:

1
2
return (stack[top]);
		top--;


to

 
return (stack[top--]);


And that did the trick. Can anyone explain why this worked, and also help me with making a template.. Thanks.
return exits the function. So your top-- line is never being executed.


Thanks for that.. Trying to figure out how to quote you lol.
Last edited on
Topic archived. No new replies allowed.