namespace ArrayStack
{
class MyStack
{
public int[] array;
public int max;
public int count = 0;
public MyStack(int size)
{
array = new int[size];
max = size;
}
/// <summary>
/// the number of elements in the stack
/// </summary>
/// <returns></returns>
public int Count()
{
return count;
}
/// <summary>
/// get the top element of the stack
/// </summary>
/// <exception cref="Exception"></exception>
public void Peak()
{
if (count == 0)
{
throw new Exception("no elements in stack");
}
Console.WriteLine("Peaked element now is: " + array[count-1]);
}
/// <summary>
/// get the top element of the stack, and remove it from the stack
/// </summary>
/// <exception cref="Exception"></exception>
public void Pop()
{
if (count == 0)
{
throw new Exception("no elements in stack");
}
Console.WriteLine("poped element is:" + array[count - 1]);
int[] NewArray = new int[count];
for (int i = count -2; i >=0 ; i--)
NewArray[i] = array[i]; //
array = NewArray;
count--;
}
/// <summary>
/// Add one element into the stack, take O(1) time.
/// </summary>
/// <param name="item">what you want to add</param>
/// <exception cref="Exception"></exception>
public void Push(int item)
{
if (max == 0)
{
throw new Exception("insufficient length of stack");
}
else
{
array[count] = item;
count++;
}
}
/// <summary>
/// display the elements in the stack
/// </summary>
public void display() //display the list
{
Console.WriteLine("your stack now contains:");
Console.WriteLine(" ");
for (int j = 0; j < array.Length; j++)
{
Console.WriteLine(array[j]);
}
Console.ReadLine();
}
}
static class Program
{
static void Main(string[] args)
{
Console.Write("Input the length of your stack:");
int StackLength = int.Parse(Console.ReadLine());
MyStack Stack = new MyStack(StackLength);
Console.WriteLine(" ");
Console.Write("how many numbers you want to push?");
int num = int.Parse(Console.ReadLine());
Console.WriteLine(" ");
if (num > StackLength)
{
Console.Write("Numbers cannot exceed your stack length, reinput numbers:");
num = int.Parse(Console.ReadLine());
}
//添加元素
for (int k = 0; k < num; k++)
{
Console.Write("A number you want to push to your stack?");
int newElement = int.Parse(Console.ReadLine());
Stack.Push(newElement); //添加元素
}
Stack.display();
Stack.Peak();
Console.Write("how many numbers you want to pop?");
int num_2 = int.Parse(Console.ReadLine());
Console.WriteLine(" ");
for (int j = 0; j < num_2; j++)
{
Stack.Pop(); //删除最上层元素
}
Console.WriteLine("Count of numbers in stack is: " + Stack.Count());
Stack.display();
Console.Write("Let's push another number into the stack:");
int newElement_2 = int.Parse(Console.ReadLine());
Stack.Push(newElement_2);
Stack.display();
Console.WriteLine("Count of numbers in stack is: " + Stack.Count());
}
}
}
Stack Task 02/15 O(n) Time complexity
于 2022-02-15 17:08:06 首次发布