DS 06 Stack
DS 06 Stack
Video Lecture
Lecture No. 6
Stack
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chis
hti International Islamic University H-10, Islamabad, Pakistan
Stacks
Stacks in real life: stack of books, stack of plates
Add new items at the top
Remove an item at the top
Stack data structure similar to real life: collection of elements arranged in a
linear order.
Can only access element at the top
Stack Operations
Push(X) – insert X as the top element of the stack
Pop() – remove the top element of the stack and return it.
Top() – return the top element without removing it from the stack.
Stacks Operations
top 1
top 7 7
top 5 5 5
top 2 2 2 2
top push(2) push(5) push(1)
push(7)
top 21
top 7 top 7
7
5 5 5 top 5
2 2 2 2 top 2
top 1 head
7
1 7 5 2
5
2
1 9 2
Example 2: Stack Using Linked List
newNode -> data = Data ; Stack :: ~Stack( ){
newNode -> next = head ; Node *current ;
head = newNode ; while ( head != NULL ){
} current = head ;
Type Stack :: Pop( ) { head = head -> next ;
if ( Is_Empty() ){ delete current ;
cout << "Stack is empty " ; }
return -1 ; }
} int main( ){
Node *current ;
Type Data ; Stack s ;
current = head ; s.Push (11); s.Push (22); s.Push (33);
Data = current -> data ; cout << s.Pop() << endl;
head = head -> next ; cout << s.Pop() << endl;
delete current ; cout << s.Pop() << endl;
return Data ; cout << s.Pop() << endl;
} system("PAUSE");
return 0;
}
3 10 4
Stack: Array or List Linked List
Since both implementations support stack operations in constant time, any
reason to choose one over the other?
Allocating and deallocating memory for list nodes does take more time than
pre-allocated array.
Linked List uses only as much memory as required by the nodes; array requires
allocation ahead of time.
Linked List Pointers (head, next) require extra memory.
Array has an upper limit; List is limited by dynamic memory allocation.
Applications of Stack
Infix expression into its postfix equivalent, or prefix equivalent so that We do
not need to maintain operator ordering, and parenthesis.
After converting into prefix or postfix notations, we have to evaluate the
expression using stack to get the result.
When we make a call from one function to the another function. The address
of the calling function gets stored in the Stack.
Stack can be used for parenthesis checking in our code.
Stack can be used to reverse a string by pushing all letters on stack and then
popping them out.
We need stack in Backtracking algorithms so that we come back to the
previous state and go into some other paths.
Page-visited history in a Web browser
Undo sequence in a text editor