Press "Enter" to skip to content

Stack

Hello, Stack is an Abstract Data Type. Stacks are defined like the Last in First Out (LIFO) or First in Last Out(FILO). Stack can be used with the Arrays and Linked Lists. In this example, I will try to use Stack with the Array. Stack has 3 important functions and these are;

  • Push : To add item, we use push function.
  • Pop : To delete item, we use pop function.
  • Top : To show top value, we use top function.

After the definitions, we can start the coding. Firstly, i define a struct and inside of the this struct, i keep the size, top and array. I define the struct name as Stack.

For the create a stack, I define a function and this function get the size value and return a stack. In the function using with the malloc function, i create an array for the stack and the size of this array will be the size which we get with the function.

For the add data to the stack, I need to define push function. Push function will not return anything for that i make the function type void. In the function, we need to check some situations like if array is full, we need to make the size of the array bigger. For the make bigger array, i create a new array and then i copy the all values of the my old array and delete from the memor using free function. I make the myfirst array equal to the other array and then i make the size times two.

For the delete data from stack, I need to define Pop function. Pop function will return a interger value for that reason i make the type of the function int. In the function, we need to check some conditions like if the top value of the array fourfold smaller than the size of the array, we need to decrease the size of the array.  For that, I create a new array and then keep the all values of the first array and then i decrease the size of the array.

For the learn top value number of the array, I create a function which return topvalue.

After the making all of the above process, I want to see the values of the stack. For that, I create a function which shows the value of the array.

Now everything is ready, we just need to write main function and create stacks.

For your questions, you can reach me via e-mail or comments.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *