Home > front end >  Adding to an array c#
Adding to an array c#

Time:04-19

I have an array int Stack[] of size 5. I want to implement a method Push(value) that will push value into the last available slot of the array. Example: if array is empty and I use Push(1), now there is a 1 on position 0 of the array; but if the array has 3 values and I use Push(1), there will be a 1 on position 3 (since the array starts at 0, for a total of 4 values in the array). How may I do this?

CodePudding user response:


public class Stack{
    int items[];
    int top;
    
    public Stack(int size){
       items=new int[size];
       top=0;
    }
   
   public void Push(int val){
         if(!IsFull()){
             items[top  ]=val;
         }     
   }
  
   public int Pop(){
      if(!IsEmpty()){
          return items[--top];
      }else{
          //-1 is for invalid op or just you can chech before calling Pop()
          //is stack empty or not
          return -1;

      }
   }

   public bool IsFull()=>top==items.Length;
   public bool IsEmpty()=>top==0;

}

CodePudding user response:

For this purpose you have List<T>

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0

Of course you can do that with an array as well, but that would mean that you have to make a new array for each Push() execution, which is completely unnecessary when you can use a list

  • Related