简体   繁体   中英

Adding to an array c#

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?

For this purpose you have List<T>

https://learn.microsoft.com/en-us/do.net/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

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM