DSA-Lect-5-Stack
DSA-Lect-5-Stack
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle.
Stack has one end, whereas the Queue has two ends (front and rear). It contains
only one pointer top pointer pointing to the topmost element of the stack.
Whenever an element is added in the stack, it is added on the top of the stack, and
the element can be deleted only from the stack. In other words, a stack can be
defined as a container in which insertion and deletion can be done from the one
end known as the top of the stack.
o It is called as stack because it behaves like a real-world stack, piles of books, etc.
o A Stack is an abstract data type with a pre-defined capacity, which means that it can
store the elements of a limited size.
o It is a data structure that follows some order to insert and delete the elements, and
that order can be LIFO or FILO.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are five
memory blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is
empty. We have taken the stack of size 5 as shown below in which we are pushing
the elements one by one until the stack becomes full.
Since our stack is full as the size of the stack is 5. In the above cases, we can observe
that it goes from the top to the bottom when we were entering the new element in
the stack. The stack gets filled up from the bottom to the top.
When we perform the delete operation on the stack, there is only one way for entry
and exit as the other end is closed. It follows the LIFO pattern, which means that the
value entered first will be removed last. In the above case, the value 5 is entered first,
so it will be removed only after the deletion of all the other elements.
o push(): When we insert an element in a stack then the operation is known as a push.
If the stack is full then the overflow condition occurs.
o pop(): When we delete an element from the stack, the operation is known as a pop.
If the stack is empty means that no element exists in the stack, this state is known as
an underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.
o count(): It returns the total number of elements available in a stack.
o change(): It changes the element at the given position.
o display(): It prints all the elements available in the stack.
AD
PUSH operation
The steps involved in the PUSH operation is given below:
POP operation
The steps involved in the POP operation is given below:
o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition
occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
Applications of Stack
The following are the applications of the stack:
o Balancing of symbols: Stack is used for balancing a symbol. For example, we have
the following program:
1. int main()
2. {
3. cout<<"Hello";
4. cout<<"Stack Programming";
5. }
As we know, each program has an opening and closing braces; when the opening
braces come, we push the braces in a stack, and when the closing braces appear, we
pop the opening braces from the stack. Therefore, the net value comes out to be
zero. If any symbol is left in the stack, it means that some syntax occurs in a program.
o String reversal: Stack is also used for reversing a string. For example, we want to
reverse a "StackProgramming" string, so we can achieve this with the help of a
stack.
First, we push all the characters of the string in a stack until we reach the null
character.
After pushing all the characters, we start taking out the character one by one until we
reach the bottom of the stack.
o UNDO/REDO: It can also be used for performing UNDO/REDO operations. For
example, we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the
text written in an editor is abc. So, there are three states, a, ab, and abc, which are
stored in a stack. There would be two stacks in which one stack shows UNDO state,
and the other shows REDO state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we
implement pop operation.
o Recursion: The recursion means that the function is calling itself again. To maintain
the previous states, the compiler creates a system stack in which all the previous
records of the function are maintained.
o DFS(Depth First Search): This search is implemented on a Graph, and Graph uses
the stack data structure.
o Backtracking: Suppose we have to create a path to solve a maze problem. If we are
moving in a particular path, and we realize that we come on the wrong way. In order
to come at the beginning of the path to create a new path, we have to use the stack
data structure.
o Expression conversion: Stack can also be used for expression conversion. This is one
of the most important applications of stack. The list of the expression conversion is
given below:
o Infix to prefix
o Infix to postfix
o Prefix to infix
o Prefix to postfix
Postfix to infix
o Memory management: The stack manages the memory. The memory is assigned in
the contiguous memory blocks. The memory is known as stack memory as all the
variables are assigned in a function call stack memory. The memory size assigned to
the program is known to the compiler. When the function is created, all its variables
are assigned in the stack memory. When the function completed its execution, all the
variables assigned in the stack are released.
Array implementation of Stack
In array implementation, the stack is formed by using the array. All the operations
regarding the stack are performed using arrays. Lets see how each operation can be
implemented on the stack using array data structure.
1. Increment the variable Top so that it can now refere to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new
element at the top of the stack.
Stack is overflown when we try to insert an element into a completely filled stack
therefore, our main function must always avoid stack overflow condition.
Algorithm:
1. begin
2. if top = n then stack full
3. top = top + 1
4. stack (top) : = item;
5. end
The underflow condition occurs when we try to delete an element from an already
empty stack.
Algorithm :
1. begin
2. if top = 0 then stack empty;
3. item := stack(top);
4. top = top - 1;
5. end;
1. int pop ()
2. {
3. if(top == -1)
4. {
5. printf("Underflow");
6. return 0;
7. }
8. else
9. {
10. return stack[top - - ];
11. }
12. }
1. Begin
2. if top = -1 then stack empty
3. item = stack[top]
4. return item
5. End
1. int peek()
2. {
3. if (top == -1)
4. {
5. printf("Underflow");
6. return 0;
7. }
8. else
9. {
10. return stack [top];
11. }
12. }
C program
1. #include <stdio.h>
2. int stack[100],i,j,choice=0,n,top=-1;
3. void push();
4. void pop();
5. void show();
6. void main ()
7. {
8.
9. printf("Enter the number of elements in the stack ");
10. scanf("%d",&n);
11. printf("*********Stack operations using array*********");
12.
13. printf("\n----------------------------------------------\n");
14. while(choice != 4)
15. {
16. printf("Chose one from the below options...\n");
17. printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
18. printf("\n Enter your choice \n");
19. scanf("%d",&choice);
20. switch(choice)
21. {
22. case 1:
23. {
24. push();
25. break;
26. }
27. case 2:
28. {
29. pop();
30. break;
31. }
32. case 3:
33. {
34. show();
35. break;
36. }
37. case 4:
38. {
39. printf("Exiting....");
40. break;
41. }
42. default:
43. {
44. printf("Please Enter valid choice ");
45. }
46. };
47. }
48. }
49.
50. void push ()
51. {
52. int val;
53. if (top == n )
54. printf("\n Overflow");
55. else
56. {
57. printf("Enter the value?");
58. scanf("%d",&val);
59. top = top +1;
60. stack[top] = val;
61. }
62. }
63.
64. void pop ()
65. {
66. if(top == -1)
67. printf("Underflow");
68. else
69. top = top -1;
70. }
71. void show()
72. {
73. for (i=top;i>=0;i--)
74. {
75. printf("%d\n",stack[i]);
76. }
77. if(top == -1)
78. {
79. printf("Stack is empty");
80. }
81. }
C++
#include <iostream>
// Function declarations
void push();
void pop();
void show();
int main() {
int choice = 0;
cin >> n;
while (choice != 4) {
switch (choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
break;
default:
return 0;
void push() {
int val;
if (top == n - 1) {
} else {
stack[top] = val;
void pop() {
if (top == -1) {
} else {
top = top - 1;
void show() {
if (top == -1) {
} else {
}
Result:
Algorithm
1. Initialization:
o Declare an integer array stack[100] to store stack elements.
o Initialize top = -1 to represent an empty stack.
o Read the number of elements (n) allowed in the stack.
2. Menu Loop:
o Display menu options: Push, Pop, Show, Exit.
o Continuously prompt the user for their choice until they choose to Exit.
3. Push Operation:
o If top == n - 1, print "Overflow" (stack is full).
o Otherwise, read the value and increment top. Assign the value to stack[top]
and print "Item pushed".
4. Pop Operation:
o If top == -1, print "Underflow" (stack is empty).
o Otherwise, print the value being popped, then decrement top.
5. Show Operation:
o If top == -1, print "Stack is empty".
o Otherwise, print all stack elements from top to 0.
6. Exit:
o Exit the program when the user chooses 4.
Pseudo Code
Start
Initialize stack[100], top = -1
Input n (number of elements in the stack)
While (choice != 4)
Display menu:
1. Push
2. Pop
3. Show
4. Exit
Input choice
If choice == 1:
Call push()
Else if choice == 2:
Call pop()
Else if choice == 3:
Call show()
Else if choice == 4:
Print "Exiting..."
Else:
Print "Please enter a valid choice"
End While
End
Procedure push()
If top == n - 1
Print "Overflow"
Else
Input value
Increment top by 1
stack[top] = value
Print "Item pushed"
End Procedure
Procedure pop()
If top == -1
Print "Underflow"
Else
Print "Item popped: stack[top]"
Decrement top by 1
End Procedure
Procedure show()
If top == -1
Print "Stack is empty"
Else
For i = top down to 0
Print stack[i]
End Procedure
1. Global Variables:
o stack[100]: An array to represent the stack, with a maximum size of 100.
o top = -1: Indicates the current position of the stack. Initially set to -1 to
show that the stack is empty.
o n: The maximum number of elements that the user wants to allow in the stack.
2. Main Function:
o int main(): The main function manages the flow of the program. It prompts
the user for the number of elements (n) in the stack and displays the stack
menu for operations (Push, Pop, Show, Exit).
o The while loop runs until the user selects 4 (Exit). Based on the user's choice,
appropriate stack operations are called.
3. Functions:
o push(): Adds an element to the top of the stack.
Checks if the stack is full (top == n - 1). If it is, prints "Overflow".
Otherwise, takes a value as input, increments top, and stores the value
in the stack at stack[top].
o pop(): Removes the top element of the stack.
Checks if the stack is empty (top == -1). If it is, prints "Underflow".
Otherwise, prints the value being removed and decrements top.
o show(): Displays all the elements in the stack.
If the stack is empty (top == -1), prints "Stack is empty".
Otherwise, iterates from top to 0 to print all elements from top to
bottom.
Example Run
1. Push 5:
o Stack: [5]
o top = 0
2. Push 10:
o Stack: [5, 10]
o top = 1
3. Push 15:
o Stack: [5, 10, 15]
o top = 2
4. Push 20:
o Since the stack is full (top = 2 which is n - 1), an "Overflow" message is
displayed.
5. Show:
o Displays:
Copy code
15
10
5
6. Pop:
o Removes 15 from the stack.
o Stack: [5, 10]
o top = 1
7. Show:
o Displays:
Copy code
10
5
8. Exit:
o The program terminates.
1. void push ()
2. {
3. int val;
4. struct node *ptr =(struct node*)malloc(sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("not able to push the element");
8. }
9. else
10. {
11. printf("Enter the value");
12. scanf("%d",&val);
13. if(head==NULL)
14. {
15. ptr->val = val;
16. ptr -> next = NULL;
17. head=ptr;
18. }
19. else
20. {
21. ptr->val = val;
22. ptr->next = head;
23. head=ptr;
24.
25. }
26. printf("Item pushed");
27.
28. }
29. }
30. Check for the underflow condition: The underflow condition occurs when
we try to pop from an already empty stack. The stack will be empty if the
head pointer of the list points to null.
31. Adjust the head pointer accordingly: In stack, the elements are popped
only from one end, therefore, the value stored in the head pointer must be
deleted and the node must be freed. The next node of the head node now
becomes the head node.
Time Complexity : o(n)
C implementation
1. void pop()
2. {
3. int item;
4. struct node *ptr;
5. if (head == NULL)
6. {
7. printf("Underflow");
8. }
9. else
10. {
11. item = head->val;
12. ptr = head;
13. head = head->next;
14. free(ptr);
15. printf("Item popped");
16.
17. }
18. }
C Implementation
1. void display()
2. {
3. int i;
4. struct node *ptr;
5. ptr=head;
6. if(ptr == NULL)
7. {
8. printf("Stack is empty\n");
9. }
10. else
11. {
12. printf("Printing Stack elements \n");
13. while(ptr!=NULL)
14. {
15. printf("%d\n",ptr->val);
16. ptr = ptr->next;
17. }
18. }
19. }
1. #include <stdio.h>
2. #include <stdlib.h>
3. void push();
4. void pop();
5. void display();
6. struct node
7. {
8. int val;
9. struct node *next;
10. };
11. struct node *head;
12.
13. void main ()
14. {
15. int choice=0;
16. printf("\n*********Stack operations using linked list*********\n");
17. printf("\n----------------------------------------------\n");
18. while(choice != 4)
19. {
20. printf("\n\nChose one from the below options...\n");
21. printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
22. printf("\n Enter your choice \n");
23. scanf("%d",&choice);
24. switch(choice)
25. {
26. case 1:
27. {
28. push();
29. break;
30. }
31. case 2:
32. {
33. pop();
34. break;
35. }
36. case 3:
37. {
38. display();
39. break;
40. }
41. case 4:
42. {
43. printf("Exiting....");
44. break;
45. }
46. default:
47. {
48. printf("Please Enter valid choice ");
49. }
50. };
51. }
52. }
53. void push ()
54. {
55. int val;
56. struct node *ptr = (struct node*)malloc(sizeof(struct node));
57. if(ptr == NULL)
58. {
59. printf("not able to push the element");
60. }
61. else
62. {
63. printf("Enter the value");
64. scanf("%d",&val);
65. if(head==NULL)
66. {
67. ptr->val = val;
68. ptr -> next = NULL;
69. head=ptr;
70. }
71. else
72. {
73. ptr->val = val;
74. ptr->next = head;
75. head=ptr;
76.
77. }
78. printf("Item pushed");
79.
80. }
81. }
82.
83. void pop()
84. {
85. int item;
86. struct node *ptr;
87. if (head == NULL)
88. {
89. printf("Underflow");
90. }
91. else
92. {
93. item = head->val;
94. ptr = head;
95. head = head->next;
96. free(ptr);
97. printf("Item popped");
98.
99. }
100. }
101. void display()
102. {
103. int i;
104. struct node *ptr;
105. ptr=head;
106. if(ptr == NULL)
107. {
108. printf("Stack is empty\n");
109. }
110. else
111. {
112. printf("Printing Stack elements \n");
113. while(ptr!=NULL)
114. {
115. printf("%d\n",ptr->val);
116. ptr = ptr->next;
117. }
118. }
119. }
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
};
Node* head = nullptr;
void push() {
int val;
Node* ptr = new Node();
if (ptr == nullptr) {
cout << "Not able to push the element" << endl;
} else {
cout << "Enter the value: ";
cin >> val;
ptr->val = val;
ptr->next = head;
head = ptr;
cout << "Item pushed" << endl;
}
}
void pop() {
if (head == nullptr) {
cout << "Underflow" << endl;
} else {
Node* ptr = head;
head = head->next;
delete ptr;
cout << "Item popped" << endl;
}
}
void display() {
Node* ptr = head;
if (ptr == nullptr) {
cout << "Stack is empty" << endl;
} else {
cout << "Printing stack elements: " << endl;
while (ptr != nullptr) {
cout << ptr->val << endl;
ptr = ptr->next;
}
}
}
int main() {
int choice = 0;
cout << "\n********* Stack operations using linked list *********\n";
cout << "\n----------------------------------------------\n";
while (choice != 4) {
cout << "\n\nChoose one from the below options...\n";
cout << "\n1. Push\n2. Pop\n3. Show\n4. Exit\n";
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
cout << "Exiting..." << endl;
break;
default:
cout << "Please enter a valid choice" << endl;
}
}
return 0;
}
Algorithm:
1. Initialize a head pointer to nullptr representing the start of the linked list.
2. Provide the following options in a loop until the user chooses to exit:
o Option 1: Push
Create a new node.
Insert the new node at the top of the stack (linked list).
o Option 2: Pop
Remove the top node from the stack.
o Option 3: Display
Display all nodes in the stack from top to bottom.
o Option 4: Exit
Exit the program.
3. Handle any invalid choices by asking the user to enter a valid option.
Pseudocode:
Start
Initialize head = null
While (choice != 4)
Print "Choose an option:"
Print "1. Push 2. Pop 3. Show 4. Exit"
Read choice
If choice == 1
Call push()
Else if choice == 2
Call pop()
Else if choice == 3
Call display()
Else if choice == 4
Print "Exiting..."
Else
Print "Invalid choice"
End If
End While
End
Function push():
Create new node
If new node == null
Print "Not able to push element"
Else
Print "Enter value"
Read value
Assign value to new node
Set new node's next to head
Set head to new node
Print "Item pushed"
End If
End Function
Function pop():
If head == null
Print "Underflow"
Else
Assign head to temporary node
Set head to head's next
Delete temporary node
Print "Item popped"
End If
End Function
Function display():
If head == null
Print "Stack is empty"
Else
Print "Printing stack elements"
Set temp = head
While temp != null
Print temp's value
Set temp to temp's next
End While
End If
End Function
The given C++ program implements a stack using a linked list. Here's an in-depth
explanation of the various components: