Lecture - Stack ADT PDF
Lecture - Stack ADT PDF
(1)
Stack ADT
Dr Muhammad Hussain
(2)
Stack ADT
An ADT that manages data elements linearly but provides access at only one end i.e. data elements can be inserted and removed from one end only. insert (Push) remove (pop)
34 14 23 8 6 2
34 14 23 8 6 2 14 23 8 6 2 34
NOTE: In Stack ADT, the elements are removed only in the inverse order of f th their i arrival i li i.e. th the last l t inserted i t d element l t is i removed d first fi t of f all. ll So, it has lastlast-in/firstin/first-out (LIFO) behavior.
Dr Muhammad Hussain Lecture - Stack ADT
(3)
Dr Muhammad Hussain
(4)
void push(Type)
Type pop()
Dr Muhammad Hussain
(5)
n -1 1
Array
Dr Muhammad Hussain Lecture - Stack ADT
(6)
(7)
Implementation of Operations
public ArrayStack(int n) { maxsize = n; top = -1; nodes = (T[]) new Object[n]; } public boolean empty() { return top == -1; }
Dr Muhammad Hussain
(8)
Implementation of Operations
public boolean full() { return top == maxsize - 1; } public void push(T e) { if(full()) return; top++; nodes[top] d [t ] = e; }
Dr Muhammad Hussain
(9)
Implementation of Operations
public T pop(){ if(!empty()) return nodes[top--]; }
Dr Muhammad Hussain
(10)
Dr Muhammad Hussain
(11)
Implementation of Operations
public LinkStack() { top = null; } public boolean empty() { return t top t == null; ll } public bli b boolean l f ll() full { return false; }
Dr Muhammad Hussain Lecture - Stack ADT
(12)
Implementation of Operations
public void push(T e) { Node<T> tmp = new Node(e); tmp.next = top; top = tmp; } public T pop() { Node<T> tmp = top; T e = top.data; top = top.next; return e; }
Dr Muhammad Hussain Lecture - Stack ADT
(13)
Performance Comparison
Array Based Implementation - An array y based implementation p suffers from the drawback that all the storage space must be reserved in advance and the maximum depth of the stack is limited to this arrays size. - Time complexity of all stack operations is O(1). O(1) Linked List based Implementation - The time complexity of all operations is O(1). For applications in which the maximum stack size is known ahead of time, an array is suitable If the maximum stack size is not known beforehand beforehand, we can use a linked list
Dr Muhammad Hussain
(14)
(15)
(16)
Dr Muhammad Hussain