Quick actions

cmd+k|ctrl+k

Navigation

Languages

StackUsingArrayList

Snippet info

Language

Csharp

Visibility

public

Author

anna1.1

Created

2020-07-17T10:53:11Z

Updated

2020-07-17T10:53:11Z

using System;
using System.Collections;

class Stack
{
    private ArrayList array;

    public Stack()
    {
        array = new ArrayList();
    }

    static void Main(string[] args)
    {
        Stack s = new Stack();
        s.Push(10);
        s.Push(16);
        s.Push(100);
        s.Pop();
        s.printStack();
        
    }

    public int? Peek()
    {
        if (array.Count > 0)
            return (int)array[array.Count - 1]; //end / last /  latest added
        return null; 
    }

    public void Push(int value)
    {
        array.Add(value);
    }

    public int? Pop()
    {
        if (array.Count == 0)
        {
            return null;
        }

        int lastItem = (int)array[array.Count - 1];
        array.RemoveAt(array.Count - 1);
        return lastItem;
    }

    public void printStack()
    {
        for(int i = array.Count  - 1; i >= 0 ; i--) //foreach index from top, write array item and go down 
        {
            Console.WriteLine(array[i]);
        }
    }
}
INFO