Placing & deleting element(s) from a object (stack)
Initializing 2 stack objects:
Stack s1 = new Stack(), s2 = new Stack();
开发者_JAVA百科
s1 = 0 0 0 0 0 0 0 0 0 0 (array of 10 elements which is empty to start with) top:0
const int Rows = 10;
int[] Table = new int[Rows];
public void TableStack(int[] Table)
{
for (int i=0; i < Table.Length; i++)
{
}
}
My question is how exactly do I place a element on a stack (push) or take a element from the stack (pop) as the following:
Push:s1.Push(5); // s1 = 5 0 0 0 0 0 0 0 0 0 (top:1)
s1.Push(9); // s1 = 5 9 0 0 0 0 0 0 0 0 (top:2)
Pop:
int number = s1.Pop(); // s1 = 5 0 0 0 0 0 0 0 0 0 0 (top:1) 9 got removed
Do I have to use get & set, and if so how exactly do I implement this with a array? Not really sure what to exactly use for this. Any hints highly appreciated.
The program uses the following driver to test the Stack class (which cannot be changed or modified):
public void ExecuteProgram()
{
Console.Title = "StackDemo";
Stack s1 = new Stack(), s2 = new Stack();
ShowStack(s1, "s1");
ShowStack(s2, "s2");
Console.WriteLine();
int getal = TryPop(s1);
ShowStack(s1, "s1");
TryPush(s2, 17);
ShowStack(s2, "s2");
TryPush(s2, -8);
ShowStack(s2, "s2");
TryPush(s2, 59);
ShowStack(s2, "s2");
Console.WriteLine();
for (int i = 1; i <= 3; i++)
{
TryPush(s1, 2 * i);
ShowStack(s1, "s1");
}
Console.WriteLine();
for (int i = 1; i <= 3; i++)
{
TryPush(s2, i * i);
ShowStack(s2, "s2");
}
Console.WriteLine();
for (int i = 1; i <= 6; i++)
{
getal = TryPop(s2);
//use number
ShowStack(s2, "s2");
}
}/*ExecuteProgram*/
You could use the built in Stack<T>
which will give you push, pop, peek etc.
The Stack object has Push and Pop methods on it. Simply call s1.Push and s1.Pop exactly as you have shown.
Hint: you need to maintain the index of the topmost element in your internal array in the Stack
class.
I’m not sure what you mean by get/set but chances are, you don’t need that here (in particular if you actually meant properties).
精彩评论