0% found this document useful (0 votes)
21 views12 pages

221066_ADS Assignment-1

Uploaded by

shivam.22311902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views12 pages

221066_ADS Assignment-1

Uploaded by

shivam.22311902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Name: Shivam Sanjay Koli

Roll No.: 221066

PRN: 22311902

Batch: SY-A3

PROBLEM STATEMENT:
Implement Stack and its operations using Linked List.

OBJECTIVES:
1. To understand the concept of the stack data structure and its properties.
2. To implement the stack using an array in Java.
3. To develop methods for basic stack operations such as push, pop, and
peek.
4. To implement error handling for underflow (popping from an empty
stack) and overflow (pushing into a full stack) conditions.
5. To create a menu-driven program that allows users to interact with the
stack, performing operations dynamically.
6. To learn how to check if the stack is empty or full using appropriate
conditions.
7. To gain practical experience in managing data using the Last-In-First-
Out (LIFO) principle.
SYSTEM REQUIREMENTS:
Minimum Hardware Requirements
MEMORY (RAM): 2GB
Hard Disk Capacity: 40GB
Processor Speed: 1.6 GHz or faster processor
Minimum Software Requirements
Operating System: Windows / Linux
Editor: Notepad/sublime/Visula Studio Code/ Atom
Browser: Chrome/ Microsoft Edge / Mozila Firefox / Safari /Opera

THEORY:
A stack is a linear data structure that operates on the principle of Last In, First
Out (LIFO). This means the last element added to the stack is the first one to be
removed. Stacks are an essential tool in programming, commonly used for
managing function calls, recursion, expression evaluation, and other operations
requiring temporary storage.

Key Concepts

1. LIFO Principle:
- In a stack, the most recently added element is removed first, adhering to the
Last In, First Out (LIFO) principle.
- For instance, consider a stack of books: the last book placed on the top will
be the first one removed.

2. Basic Stack Operations:


- Push: Adds a new element to the top of the stack.
- Pop: Removes and returns the top element from the stack.
- Peek (or Top): Retrieves the top element without removing it.
- isEmpty: Checks whether the stack is empty.
- isFull: Determines if the stack has reached its maximum capacity (in case of
a fixed-size stack).

3. Implementation Using an Array:


- A stack can be implemented using an array, where the stack grows from one
end.
- The variable `top` keeps track of the index of the last element in the stack.
- The size of the array limits the number of elements the stack can hold.

4. Stack Underflow and Overflow:


- Underflow: Occurs when attempting to pop an element from an empty stack.
In this scenario, `top` is -1, indicating no elements are available for removal.
- Overflow: Happens when attempting to push an element into a full stack.
This occurs when `top` equals the maximum index of the array, signaling that
no more elements can be added.

5. Menu-Driven Program:
- A menu-driven program enables user interaction with the stack through
simple options to perform operations like push, pop, peek, and check the stack's
status.
- This interactive interface makes it easier for users to understand and
manipulate the stack's behavior.

CODE:
import java.util.Scanner;

class StackLL {
class node {
int data;
node next = null;
}

node head = null;


int height = 0;
int capacity = 0;
StackLL(int capacity) {
head = new node();
this.capacity = capacity;
}
// Method to push an element onto the stack

void push(int p) {
if (height == capacity) {
System.out.println("The stack is full");
} else {
node temp = new node();
temp.data = p;
temp.next = head;
head = temp;
height++;
}
}

void pop() {
if (height == 0) {
System.out.println("The stack is empty");
} else {
head = head.next;
height--;
}
}

int peek() {
return head.data;
}

void display() {
if (height == 0) {
System.out.println("The stack is empty");
} else {
node temp = head;
while (temp.next != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
}
}

public class Main {


static void LL() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the capacity of stack : ");
int size = sc.nextInt();
StackLL st = new StackLL(size);
int option;
do {
System.out.println("1. Push element\n2. Pop element\n3.
Peek element\n4. Display\n5. Exit\nEnter the option : ");
option = sc.nextInt();
switch (option) {
case 1: {
System.out.println("Enter th data that you want to
push : ");
st.push(sc.nextInt());

}
break;
case 2: {
st.pop();
}
break;
case 3: {
if (st.height == 0) {
System.out.println("The stack is empty");
} else {
System.out.println("The top most element in
stack is " + st.peek());
}
}
break;
case 4: {
st.display();
}
break;
case 5: {
System.out.println("Exiting.");
}
break;
default: {
System.out.println("Incorrect Option.");
}
break;
}

} while (option != 5);


}

public static void main(String[] args) {


// TODO Auto-generated method stub
LL();
}

SAMPLE INPUT AND OUTPUT:

1. Stack using Linked List


2. Stack using Array
3. Exit
Enter the option :
1
Enter the capacity of stack :
3
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
1
Enter th data that you want to push :
5
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
1
Enter th data that you want to push :
8
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
1
Enter th data that you want to push :
1
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
4
1
8
5
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
1
Enter th data that you want to push :
6
The stack is full
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
4
1
8
5
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
2
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
4
8
5
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
3
The top most element in stack is 8
1. Push element
2. Pop element
3. Peek element
4. Display
5. Exit
Enter the option :
5
Exiting.

CONCLUSION:
This program implements a simple stack using an array in Java. It demonstrates
core stack operations such as push, pop, and peek while addressing important
conditions like underflow and overflow. By exploring this implementation,
users gain a deeper understanding of how the LIFO principle governs data flow
and how stacks manage memory efficiently in various applications.
Problem Statement:
Convert infix expression to postfix expression using stack.

Objective:
The goal of this assignment is to understand the application of stacks in
transforming infix expressions into postfix. This involves analyzing operator
precedence, associativity, and efficient use of stack operations. The exercise
demonstrates the importance of postfix expressions in simplifying arithmetic
evaluation and eliminating ambiguities inherent in infix notation.

SYSTEM REQUIREMENTS:
Minimum Hardware Requirements
MEMORY (RAM): 2GB
Hard Disk Capacity: 40GB
Processor Speed: 1.6 GHz or faster processor
Minimum Software Requirements
Operating System: Windows / Linux
Editor: Notepad/sublime/Visula Studio Code/ Atom
Browser: Chrome/ Microsoft Edge / Mozila Firefox / Safari /Opera

Theory:
Mathematical expressions can be represented in three notations: infix, postfix,
and prefix.
 Infix Notation: Operators are placed between operands (e.g., a + b). It is
the standard human-readable format but can lead to ambiguity without
parentheses due to precedence and associativity rules.
 Postfix Notation (Reverse Polish Notation): Operators are placed after
operands (e.g., a b +). It eliminates the need for parentheses and operator
precedence, making it straightforward for computers to evaluate.
The stack data structure provides an efficient mechanism for converting infix
expressions to postfix. During conversion, the stack temporarily stores operators
and parentheses, ensuring that precedence and associativity are respected.
Key Conversion Principles:
1. Operands are added directly to the result.
2. Operators are pushed to the stack, but only after popping operators from
the stack that have higher or equal precedence.
3. Parentheses explicitly dictate precedence:
o A left parenthesis (() is pushed onto the stack.
o A right parenthesis ()) causes operators to be popped and added to
the result until a left parenthesis is encountered (the left parenthesis
is discarded).

Algorithm:
1. Initialize an empty stack (`st`) and an empty result string (`result`).
2. Input the infix expression to be converted.
3. Process each character in the infix expression sequentially:
- Operand: Append directly to the result string.
- Opening Parenthesis (`(`): Push onto the stack.
- Closing Parenthesis (`)`):
- Pop and append operators from the stack to the result until a left
parenthesis (`(`) is found.
- Discard the left parenthesis.
- Operator*:
- If the stack is empty, push the operator onto the stack.
- Otherwise:
- Pop and append operators from the stack to the result while the
precedence of the top operator on the stack is higher or equal to the current
operator.
- Push the current operator onto the stack.
4. After processing all characters, pop remaining operators from the stack and
append them to the result.
5. Output the final postfix expression.

Code:
package main;
import java.util.*;
public class Main {
public static int precednce(char a) {
switch(a){
case '+':{
return 1;
}
case '-':{
return 1;
}
case '*':{
return 2;
}
case '/':{
return 2;
}
case '^':{
return 3;
}

}
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack<Character> st=new Stack<>();
String infix;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the infix expression: ");
infix=sc.nextLine();
StringBuilder result=new StringBuilder();
for(int i =0;i<infix.length();i++) {
char temp=infix.charAt(i);
if(Character.isLetterOrDigit(temp)) {
result.append(temp);
}else if(temp=='(') {
st.push(temp);
}else if(temp==')') {
while((!st.isEmpty())&&st.peek()!='(')
{
result.append(st.pop());
}
st.pop();
}else {
if(!st.empty()) {

if(precednce(temp)>precednce(st.peek())) {
st.push(temp);
}else {
while((!st.empty())&&(!
(precednce(temp)>precednce(st.peek())))) {

result.append(st.pop());
}
st.push(temp);
}
}else {
st.push(temp);
}
System.out.println("Contents of stack:
");
System.out.println(st.toString());
System.out.println("Postfix expression:
");
System.out.println(result.toString());
}
}
while(!st.empty()) {
result.append(st.pop());
}
System.out.println("Final postfix expression: ");
System.out.println(result.toString());
}

Sample input and output:


Enter the infix expression:
a-b*c-d/e+f
Contents of stack:
[-]
Postfix expression:
a
Contents of stack:
[-, *]
Postfix expression:
ab
Contents of stack:
[-]
Postfix expression:
abc*-
Contents of stack:
[-, /]
Postfix expression:
abc*-d
Contents of stack:
[+]
Postfix expression:
abc*-de/-
Final postfix expression:
abc*-de/-f+

Conclusion:
In this assignment, we successfully implemented the conversion of an infix
expression to a postfix expression using a stack. The algorithm efficiently
handles operators, operands, and parentheses by following the rules of operator
precedence and associativity. By using the stack to temporarily hold operators,
the program ensures that the postfix expression is generated without the need
for parentheses, making it easier to evaluate computationally. This approach
demonstrates the practical application of stack data structures in parsing and
expression evaluation.

You might also like