2018-06-29
##A stack is a data structure that occasionally known as LIFO (Last In First Out), meaning that the last element added to the stack must be the first element removed from it.
####The simplest way to understand stack, Box of books. We add the first one on bottom then the next on top and so on. If we want to choose any one, we should remove all books above it. for example if we want to get the last book in the box, we will remove all books on top of this book.
#By stack we can: Push(Key) : adds key to collection Key Top() : returns the most recently added key Key Pop() : removes and returns most recently added key Boolean Empty() : are there any elements?????
##Here stack implementation
{% gist https://gist.github.com/mohamedkhaledyousef/8751538e1d981b1db4a9d80678d18af0 %}
##We can also create stack using STL : {% gist https://gist.github.com/mohamedkhaledyousef/7aa2ff6e6378d7db50ca29d6b6a5caa7 %}
##Last thing to say, One of the application of a stack is Balanced Brackets,
###Here the problem Input : A string str consisting of ‘(‘ , ‘)’ , ‘[‘ , ‘]’ characters Output: returns whether or not the string’s parentheses and square brackets balanced For examples: Balanced like this: “ ([]) “ “ ((([([])]))()) “ Unbalanced like this: “ ([]]() “ “ ][ “
##Algorithm
IsBalanced(str )
Stack stack //create stack
for char in str: //for every character in string
if char in [‘(‘, ‘[‘]:
stack.Push(char )
else:
if stack.Empty(): //means false ,not matches
return False
top <- stack.Pop()
if (top = ‘[‘ and char != ‘]’) or (top = ‘(‘ and char != ‘)’):
return False //dont match
return stack.Empty()
##Here the code :
{% gist https://gist.github.com/mohamedkhaledyousef/ca843cb6a521999363c6592990078e1b %}
##You must know that: 1. Stacks are used for compilers and a lot of algorithms 2. We can also implement stack with linked list
3. Stacks are known as LIFO (Last In First Out) or GIGO (Garbage In Garbage Out)
###Last thing to say, Thanks for reading and I hope it would help and don’t hesitate to tell me your feedback and suggestions :)) #All source codes in c++ in this [repo](https://github.com/mohamedkhaledyousef/Crash-courses/tree/master/Stack