Dsa Exp1
Dsa Exp1
Problem Statement:
Understand basic Stack operations like Push, Pop, Peek, Size of the stack.
Theory:
● A stack is a linear data structure that follows the Last In, First Out (LIFO) principle,
meaning that the last element added to the stack is the first one to be removed. The stack
Abstract Data Type (ADT) supports essential operations such as push (insertion), pop
(deletion), peek (viewing the top element), and isEmpty/isFull (checking stack
status).
● Stacks are widely used in applications like expression evaluation, function call
management in recursion, and backtracking algorithms.
● A stack is a container of objects that are inserted and removed according to the
last-in-first out ( LIFO ) principle.
● Objects can be inserted at any time, but only the last (the most-recently inserted) object
can be removed.
● Inserting an item is known as “pushing” onto the stack.
● “Popping” off the stack is synonymous with removing an item
Approach:
A stack can be implemented using arrays (static implementation) or linked lists (dynamic
implementation). Here, we focus on an array-based implementation.Pseudocode given below
explains basic operations to be implemented.
ELSE
END IF
END FUNCTION
IF s.top == -1 THEN
RETURN -1
ELSE
RETURN ELEMENT
END IF
END FUNCTION
Advantages:
Disadvantages:
int main() {
int choice, value;
while (1) {
printf("\n1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
value = pop();
if (value != -1)
int pop() {
if (top == -1) {
printf("Stack Underflow!\n");
return -1;
}
return stack[top--];
}
int peek() {
if (top == -1) {
printf("Stack is empty!\n");
return -1;
}
return stack[top];
}
void display() {
if (top == -1) {
printf("Stack is empty!\n");
return;
}
printf("Stack: ");
for (int i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
}
Conclusion
The stack ADT provides a structured way to store and manage data using the LIFO principle.
The array-based implementation offers efficient and fast operations, making it ideal for use cases
like function call stacks, undo mechanisms, and expression evaluation. However, for dynamic
memory allocation and flexibility, a linked list-based implementation can be considered.
Evaluation: -