Stack
Stack
[email protected] 1
Stack and Queue
inserted.
A queue is a first in, first out (FIFO) data structure
Items are removed from a queue in the same order as they were inserted.
2 2
Stack: Last In First Out
A stack is a list with the restriction that insertions and deletions can be
performed in only one position, namely, the top of the stack.
The operations: push (insert) and pop (delete)
3 3
Application of Stack
Direct applications
Page-visited history in a Web browser
Saving local variables when one function calls another, and this one
calls another, and so on.
Indirectapplications
Auxiliary data structure for algorithms
4 4
Array Implementation of Stack
To implement a stack, items are inserted and removed at the same end (called the
top)
To use an array to implement a stack, you need both the array itself and an
integer
The integer tells you either:
5 5
Stacks by Array: Push and Pop
When you pop an element, do you just leave the “deleted” element sitting in
the array?
The surprising answer is, “it depends”
If this is an array of primitives, or if you are programming in C or C++,
7
Stacks by Array: Error Checking
8
Stacks by Array: PUSH() & POP()
• Sample Question:
Show the status of a STACK implemented by an array of size, m=5 for
the operations: push(10), push(20), pop(), push(30),push(40), pop(), pop(),
pop().
Initial stack, top = -1 Pop() , top = 0 Pop() , top = 1
10 10 30
10 10 30 10
10 20 10 30 40
10
Linked List Implementation of Stack
Since all the actions happen at the top of a stack, a singly-linked list (SLL) is a
fine way to implement it
The header of the list points to the top of the stack
Pushing is inserting an element at the front of the list
Popping is removing an element from the front of the list
11
Linked List Implementation of Stack
12
Push() Implementation – Linked List
struct Node {
int value;
struct Node* next;
};
struct Node* top;
void push(int data) {
struct Node* temp;
temp = (struct Node *)malloc(sizeof(struct
Node));
int pop(){
struct Node* temp;
int data;
if (top == NULL) {
cout << "\n Stack Underflow" << endl;
exit(1);
}
else {
data = top->value;
temp = top;
top = top->next;
free(temp);
return data;
}
}
14
QUEUE
15
Queue: First In First Out
A Queue is an ordered collection of items from which items may be removed at one
end (called the front of the queue) and into which items may be inserted at the other
end (the rear of the queue).
The operations: enqueue (insert) and dequeue (delete)
16
Queue
• Sample Question:
Show the status of a QUEUE for the following operations, where the QUEUE is implemented
by an array of size, m=3. Enqueue(164), Enqueue(83), Dequeue(), Enqueue(80), Enqueue(75),
Dequeue()
Initial queue, front=rear = -1 Dequeue(), front =1, rear =1 Dequeue(), front =2, rear =2
83 80
164 83 80
164 83 83 80
17
Thank You
18