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

comp project 2nd term

The document outlines multiple Java programs implementing data structures including a simple stack, separating odd and even numbers into two stacks, merging two stacks, and creating a simple queue. Each section includes an algorithm and code implementation, detailing operations like push, pop, enqueue, and node addition in a linked list. Variable listings and user interaction prompts are also provided for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views53 pages

comp project 2nd term

The document outlines multiple Java programs implementing data structures including a simple stack, separating odd and even numbers into two stacks, merging two stacks, and creating a simple queue. Each section includes an algorithm and code implementation, detailing operations like push, pop, enqueue, and node addition in a linked list. Variable listings and user interaction prompts are also provided for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

27.

PROGRAM TO IMPLEMENT A SIMPLE STACK IN JAVA


Algorithm for Simple Stack Program

1. Initialize the stack:


o Create an array stack[] to store stack elements.
o Initialize top = -1 to indicate an empty stack.
2. Start a loop to display menu options:
o Display the following choices to the user:
1. Push
2. Pop
3. Peek
4. Exit
3. Take user input to select an operation.
4. Perform the corresponding operation based on the user input:
o Push Operation:
 If top == 4, display "Stack is full" (since stack size is 5).
 Otherwise:
 Increment top.
 Add the new value to stack[top].
 Display the pushed value.
o Pop Operation:
 If top == -1, display "Stack is empty."
 Otherwise:
 Display the popped value from stack[top].
 Decrement top.
o Peek Operation:
 If top == -1, display "Stack is empty."
 Otherwise:
 Display the value at stack[top] without removing it.
5. Exit the loop when the user selects the exit opti
import java.util.Scanner;

public class SimpleStack {

public static void main(String[] args) {

int[] stack = new int[5]; // Stack size of 5

int top = -1; // Indicates an empty stack

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Push");

System.out.println("2. Pop");

System.out.println("3. Peek");

System.out.println("4. Exit");

int choice = scanner.nextInt();

switch (choice) {

case 1: // Push operation

if (top == 4) {

System.out.println("Stack is full."); } else {

System.out.println("Enter a value to push:");

int value = scanner.nextInt();

top++;

stack[top] = value;

System.out.println("Pushed " + value); } break;

case 2: // Pop operation

if (top == -1) {

System.out.println("Stack is empty.");
} else {

System.out.println("Popped " + stack[top]);

top--;

break;

case 3: // Peek operation

if (top == -1) {

System.out.println("Stack is empty.");

} else {

System.out.println("Top element is: " + stack[top]);

break;

case 4: // Exit

System.out.println("Exiting...");

scanner.close();

return;

default:

System.out.println("Invalid choice, try again.");

}
Variable Listing

1. stack[]:
o Type: int[]
o Purpose: Array used to store stack elements. Its size is 5.
2. top:
o Type: int
o Purpose: Holds the index of the top element in the stack. Starts at -1,
indicating an empty stack.
3. scanner:
o Type: Scanner
o Purpose: Used to take user input for menu selection and stack operations (e.g.,
values to push onto the stack).
4. choice:
o Type: int
o Purpose: Stores the user's menu selection.
5. value:
o Type: int
o Purpose: Stores the value input by the user to be pushed onto the stack.
28.Write a program in java to separate two
stacks one for odd and one for even

Algorithm for Separating Odd and Even Numbers into Two Stacks

1. Initialize two stacks:


o Create an array oddStack[] to store odd numbers.
o Create an array evenStack[] to store even numbers.
o Initialize oddTop = -1 and evenTop = -1 to indicate that both stacks are initially
empty.
2. Start a loop to accept 5 numbers from the user:
o For each input:
 If the number is even (number % 2 == 0):
 Check if the even stack is full (evenTop == 4).
 If not, increment evenTop and push the number onto the
evenStack.
 If the number is odd:
 Check if the odd stack is full (oddTop == 4).
 If not, increment oddTop and push the number onto the oddStack.
3. After the loop ends, display the contents of the oddStack:
o If oddTop == -1, display "Odd stack is empty."
o Otherwise, print each element of oddStack[] from oddTop to 0.
4. Display the contents of the evenStack:
o If evenTop == -1, display "Even stack is empty."
o Otherwise, print each element of evenStack[] from evenTop to 0.
5. End of program.
import java.util.Scanner;

public class OddEvenStack {

public static void main(String[] args) {

int[] oddStack = new int[5]; // Stack to store odd numbers

int[] evenStack = new int[5]; // Stack to store even numbers

int oddTop = -1; // Indicates top of the odd stack

int evenTop = -1; // Indicates top of the even stack

Scanner scanner = new Scanner(System.in);

// Loop to allow the user to enter numbers

for (int i = 0; i < 5; i++) {

System.out.println("Enter a number:");

int value = scanner.nextInt();

if (value % 2 == 0) {

// Even number - push to even stack

if (evenTop == 4) {

System.out.println("Even stack is full."); } else {

evenTop++;

evenStack[evenTop] = value;

System.out.println("Pushed " + value + " to even stack."); } } else {

// Odd number - push to odd stack

if (oddTop == 4) {

System.out.println("Odd stack is full.");} else {

oddTop++;

oddStack[oddTop] = value;

System.out.println("Pushed " + value + " to odd stack.");

} } }

// Display the contents of the stacks

System.out.println("\nOdd Stack:");

if (oddTop == -1) {

System.out.println("Odd stack is empty.");

} else {
for (int i = oddTop; i >= 0; i--) {

System.out.println(oddStack[i]);

System.out.println("\nEven Stack:");

if (evenTop == -1) {

System.out.println("Even stack is empty.");

} else {

for (int i = evenTop; i >= 0; i--) {

System.out.println(evenStack[i]);

scanner.close();

}
Variable Listing

1. oddStack[]:
o Type: int[]
o Purpose: Stores odd numbers.
o Size: 5 (can hold up to 5 odd numbers).
2. evenStack[]:
o Type: int[]
o Purpose: Stores even numbers.
o Size: 5 (can hold up to 5 even numbers).
3. oddTop:
o Type: int
o Purpose: Keeps track of the top element's index in the odd stack.
o Initial value: -1 (indicating an empty stack).
4. evenTop:
o Type: int
o Purpose: Keeps track of the top element's index in the even stack.
o Initial value: -1 (indicating an empty stack).
5. scanner:
o Type: Scanner
o Purpose: Used to take input from the user.
6. value:
o Type: int
o Purpose: Stores the user input that will be either pushed to the odd stack or the
even stack.
29. Write a program in java to merge two
stacks

Algorithm for Merging Two Stacks

1. Initialize three stacks:


o Create stack1[] and stack2[] to store input values.
o Create an empty mergedStack[] for the merged result.
2. Take input for the first stack (stack1[]):
o Ask the user to input values and push them onto stack1.
3. Take input for the second stack (stack2[]):
o Ask the user to input values and push them onto stack2.
4. Merge stack1[] into mergedStack[]:
o While stack1 is not empty:
 Pop elements from stack1[] and push them onto mergedStack[].
5. Merge stack2[] into mergedStack[]:
o While stack2[] is not empty:
 Pop elements from stack2[] and push them onto mergedStack[].
6. Display the contents of the mergedStack[]:
o While mergedStack[] is not empty:
 Pop and print each element of mergedStack[].
7. End the program.
import java.util.Scanner;

import java.util.Stack;

public class MergeStacks {

public static void main(String[] args) {

// Create two stacks

Stack<Integer> stack1 = new Stack<>();

Stack<Integer> stack2 = new Stack<>();

Stack<Integer> mergedStack = new Stack<>();

Scanner scanner = new Scanner(System.in);

// Input for stack1

System.out.println("Enter 5 numbers for Stack 1:");

for (int i = 0; i < 5; i++) {

int value = scanner.nextInt();

stack1.push(value); }

// Input for stack2

System.out.println("Enter 5 numbers for Stack 2:");

for (int i = 0; i < 5; i++) {

int value = scanner.nextInt();

stack2.push(value); }

// Merging Stack 1 into mergedStack

System.out.println("Merging Stack 1...");

while (!stack1.isEmpty()) {

mergedStack.push(stack1.pop()); }

// Merging Stack 2 into mergedStack

System.out.println("Merging Stack 2...");

while (!stack2.isEmpty()) {

mergedStack.push(stack2.pop()); }

// Display the merged stack

System.out.println("\nMerged Stack:");

while (!mergedStack.isEmpty()) {

System.out.println(mergedStack.pop()); }

scanner.close();

}}
Variable Listing

1. stack1[]:
o Type: Stack<Integer>
o Purpose: Stores the first set of input values from the user.
2. stack2[]:
o Type: Stack<Integer>
o Purpose: Stores the second set of input values from the user.
3. mergedStack[]:
o Type: Stack<Integer>
o Purpose: Holds the merged values from both stack1[] and stack2[].
4. value:
o Type: int
o Purpose: Temporarily holds user input values to be pushed onto the stacks.
5. scanner:
o Type: Scanner
o Purpose: To take input from the user.
30.Write in java to form a queue
Algorithm for Simple Queue with Enqueue Operation

1. Initialize the queue:


o Create an array queue[] of size 5 to store the queue elements.
o Initialize front = -1 and rear = -1 to indicate that the queue is empty.
2. Start a loop to display menu options:
o Display the following options to the user:
1. Enqueue
2. Exit
3. Take user input to select an operation.
4. Perform the corresponding operation based on the user input:
o Enqueue Operation:
 If rear == 4, display "Queue is full".
 Otherwise:
 If front == -1, set front = 0 to indicate that the queue is now
non-empty.
 Increment rear.
 Add the input value to queue[rear].
 Display the enqueued value.
o Exit:
 Terminate the loop and the program.
5. Repeat the loop until the user chooses to exit.
public class SimpleQueue {

public static void main(String[] args) {

int[] queue = new int[5]; // Array to hold the queue elements

int front = -1, rear = -1; // Pointers for front and rear of the queue

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Enqueue");

System.out.println("2. Exit");

int choice = scanner.nextInt();

switch (choice) {

case 1: // Enqueue operation

if (rear == queue.length - 1) {

System.out.println("Queue is full. Cannot enqueue.");

} else {

System.out.println("Enter a value to enqueue:");

int value = scanner.nextInt();

if (front == -1) front = 0; // Set front to 0 if first element is added

rear++;

queue[rear] = value;

System.out.println("Enqueued " + value);

break;

case 2: // Exit

System.out.println("Exiting...");

scanner.close();

return;

default:

System.out.println("Invalid choice, try again.");

} }}
Variable Listing

1. queue[]:
o Type: int[]
o Purpose: Array to store the elements of the queue. Size is 5.
2. front:
o Type: int
o Purpose: Keeps track of the front of the queue. Initially -1 (queue is empty).
3. rear:
o Type: int
o Purpose: Keeps track of the rear of the queue. Initially -1 (queue is empty).
4. scanner:
o Type: Scanner
o Purpose: Used to take user input for the operation (enqueue or exit) and for the
value to be enqueued.
5. choice:
o Type: int
o Purpose: Stores the user’s menu selection (1 for enqueue, 2 for exit).
6. value:
o Type: int
o Purpose: Stores the value entered by the user to be enqueued into the queue.
31.write a program in java to make a simple link list
Algorithm for a Simple Singly Linked List

1. Node Class Definition:


o Define a Node class with:
 An integer data to store the value.
 A Node reference next to point to the next node.
2. Linked List Class Definition:
o Define a SimpleLinkedList class with:
 A Node reference head initialized to null to point to the first node.
3. Add Node Operation:
o Create a method add(int data):
 Create a new node with the given data.
 If head is null, set head to the new node (list is empty).
 Otherwise, traverse to the end of the list:
 Use a temporary variable current initialized to head.
 While current.next is not null, move current to
current.next.
 Set current.next to the new node (add the new node at the end).
4. Display List Operation:
o Create a method display():
 If head is null, print "List is empty."
 Otherwise, initialize a temporary variable current to head.
 Print "Linked List: " and traverse the list:
 While current is not null, print current.data followed by " ->
".
 Move current to current.next.
 Print "null" to indicate the end of the list.
5. Main Method:
o Create an instance of SimpleLinkedList.
o Use a loop to display menu options:
1. Add a node.
2. Display the list.
3. Exit.
o Read user input for the chosen operation.
 If the user chooses to add a node:
 Prompt for a value and call the add(value) method.
 If the user chooses to display the list:
 Call the display() method.
 If the user chooses to exit:
 Break the loop and terminate the program.
import java.util.Scanner;

// Node class to represent each element in the linked list

class Node {

int data; // Value of the node

Node next; // Pointer to the next node

// Constructor

Node(int data) {

this.data = data;

this.next = null; // Initially, the next pointer is null

public class SimpleLinkedList {

Node head; // Head of the linked list

// Method to add a new node at the end of the linked list

public void add(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode; // If the list is empty, set the head to the new node

} else {

Node current = head;

while (current.next != null) {

current = current.next; // Traverse to the end of the list

current.next = newNode; // Link the new node at the end

System.out.println("Added: " + data);

// Method to display the linked list

public void display() {

if (head == null) {

System.out.println("List is empty.");

return;
}

Node current = head;

System.out.print("Linked List: ");

while (current != null) {

System.out.print(current.data + " -> ");

current = current.next; // Move to the next node

System.out.println("null"); // Indicate the end of the list

public static void main(String[] args) {

SimpleLinkedList linkedList = new SimpleLinkedList();

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Add a node");

System.out.println("2. Display the list");

System.out.println("3. Exit");

int choice = scanner.nextInt(); // Read user choice

if (choice == 1) { // Add a node

System.out.println("Enter a value to add:");

int value = scanner.nextInt(); // Read the value to add

linkedList.add(value); // Add the value to the list } else if (choice == 2) { // Display the list

linkedList.display(); // Show the elements in the list

} else if (choice == 3) { // Exit

System.out.println("Exiting...");

break; // Exit the loop

} else {

System.out.println("Invalid choice, try again."); // Handle invalid input }}

scanner.close(); // Close the scanner }


Variable Listing:

1. Node Class:
o data: Type: int, Purpose: Holds the value of the node.
o next: Type: Node, Purpose: Points to the next node in the linked list.
2. SimpleLinkedList Class:
o head: Type: Node, Purpose: Points to the first node in the linked list.
3. Main Method:
o linkedList: Type: SimpleLinkedList, Purpose: Instance to perform operations
on the linked list.
o scanner: Type: Scanner, Purpose: Reads user input.
o choice: Type: int, Purpose: Stores the user's menu selection.
o value: Type: int, Purpose: Stores the value entered by the user to be added to the
linked list.
32.write a program in java to display the largest
element in a link list
Algorithm for Finding the Largest Element in a Singly Linked List

1. Node Class Definition:


o Define a Node class with:
 An integer data to store the value.
 A Node reference next to point to the next node.
2. Linked List Class Definition:
o Define a SimpleLinkedList class with:
 A Node reference head initialized to null to point to the first node.
3. Add Node Operation:
o Create a method add(int data):
 Create a new node with the given data.
 If head is null, set head to the new node (list is empty).
 Otherwise, traverse to the end of the list:
 Use a temporary variable current initialized to head.
 While current.next is not null, move current to
current.next.
 Set current.next to the new node (add the new node at the end).
4. Display Largest Element Operation:
o Create a method displayLargest():
 If head is null, print "List is empty."
 Initialize an integer variable largest to head.data.
 Initialize a temporary variable current to head.next.
 Traverse the linked list:
 While current is not null, compare current.data with
largest:
 If current.data is greater than largest, update
largest.
 Move current to current.next.
 Print the largest element found.
5. Main Method:
o Create an instance of SimpleLinkedList.
o Use a loop to display menu options:
1. Add a node.
2. Display the largest element.
3. Exit.
o Read user input for the chosen operation.
 If the user chooses to add a node:
 Prompt for a value and call the add(value) method.
 If the user chooses to display the largest element:
 Call the displayLargest() method.
 If the user chooses to exit:
 Break the loop and terminate the program.
import java.util.Scanner;

// Node class to represent each element in the linked list

class Node {

int data; // Value of the node

Node next; // Pointer to the next node

// Constructor

Node(int data) {

this.data = data;

this.next = null; // Initially, the next pointer is null

public class SimpleLinkedList {

Node head; // Head of the linked list

// Method to add a new node at the end of the linked list

public void add(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode; // If the list is empty, set the head to the new node

} else {

Node current = head;

while (current.next != null) {

current = current.next; // Traverse to the end of the list

current.next = newNode; // Link the new node at the end

// Method to find and display the largest element in the linked list

public void displayLargest() {


if (head == null) {

System.out.println("List is empty.");

return;

int largest = head.data; // Start with the first element as the largest

Node current = head.next; // Start checking from the second element

// Traverse the linked list

while (current != null) {

if (current.data > largest) {

largest = current.data; // Update largest if a larger element is found

current = current.next; // Move to the next node

System.out.println("The largest element in the linked list is: " + largest);

public static void main(String[] args) {

SimpleLinkedList linkedList = new SimpleLinkedList();

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Add a node");

System.out.println("2. Display the largest element");

System.out.println("3. Exit");

int choice = scanner.nextInt(); // Read user choice

if (choice == 1) { // Add a node

System.out.println("Enter a value to add:");

int value = scanner.nextInt(); // Read the value to add

linkedList.add(value); // Add the value to the list

} else if (choice == 2) { // Display the largest element

linkedList.displayLargest(); // Show the largest element


} else if (choice == 3) { // Exit

System.out.println("Exiting...");

break; // Exit the loop

} else {

System.out.println("Invalid choice, try again."); // Handle invalid input

scanner.close(); // Close the scanner

}
Variable Listing

1. Node Class:
o data:
 Type: int
 Purpose: Holds the value of the node.
o next:
 Type: Node
 Purpose: Points to the next node in the linked list.
2. SimpleLinkedList Class:
o head:
 Type: Node
 Purpose: Points to the first node in the linked list.
3. Main Method:
o linkedList:
 Type: SimpleLinkedList
 Purpose: Instance to perform operations on the linked list.
o scanner:
 Type: Scanner
 Purpose: Reads user input.
o choice:
 Type: int
 Purpose: Stores the user's menu selection.
o value:
 Type: int
 Purpose: Stores the value entered by the user to be added to the linked list.
o largest:
 Type: int
 Purpose: Stores the largest value found in the linked list.
o current:
 Type: Node
 Purpose: Temporary pointer used to traverse the linked list.
33..Write a program in java to form a
reverse link list
ALGORITHYM

Explanation:

1. Node Class:
o Represents each element in the linked list, containing:
 data: An integer value.
 next: A pointer to the next node.
2. SimpleLinkedList Class:
o Contains a pointer head to the first node of the list.
o The add(int data) method adds a new node at the end of the list.
o The reverse() method reverses the linked list:
 Uses three pointers: previous, current, and next.
 Iterates through the list, reversing the links as it goes.
 Updates head to the new front of the list after reversing.
3. Display Method:
o The display() method prints the elements in the linked list.
4. Main Method:
o Creates an instance of SimpleLinkedList.
o Uses a loop to allow the user to:
 Add a node by entering a value.
 Display the current linked list.
 Reverse the linked list.
 Exit the program.
import java.util.Scanner;

// Node class to represent each element in the linked list

class Node {

int data; // Value of the node

Node next; // Pointer to the next node

// Constructor

Node(int data) {

this.data = data;

this.next = null; // Initially, the next pointer is null

public class SimpleLinkedList {

Node head; // Head of the linked list

// Method to add a new node at the end of the linked list

public void add(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode; // If the list is empty, set the head to the new node

} else {

Node current = head;

while (current.next != null) {

current = current.next; // Traverse to the end of the list

current.next = newNode; // Link the new node at the end

// Method to reverse the linked list


public void reverse() {

Node previous = null; // Previous node

Node current = head; // Current node

Node next = null; // Next node

while (current != null) {

next = current.next; // Store the next node

current.next = previous; // Reverse the link

previous = current; // Move previous to the current node

current = next; // Move to the next node

head = previous; // Update head to the new front of the list

System.out.println("Linked list reversed.");

// Method to display the linked list

public void display() {

if (head == null) {

System.out.println("List is empty.");

return;

Node current = head;

System.out.print("Linked List: ");

while (current != null) {

System.out.print(current.data + " -> ");

current = current.next; // Move to the next node

System.out.println("null"); // Indicate the end of the list

public static void main(String[] args) {

SimpleLinkedList linkedList = new SimpleLinkedList();

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nChoose an operation:");

System.out.println("1. Add a node");


System.out.println("2. Display the list");

System.out.println("3. Reverse the list");

System.out.println("4. Exit");

int choice = scanner.nextInt(); // Read user choice

if (choice == 1) { // Add a node

System.out.println("Enter a value to add:");

int value = scanner.nextInt(); // Read the value to add

linkedList.add(value); // Add the value to the list

} else if (choice == 2) { // Display the list

linkedList.display(); // Show the elements in the list

} else if (choice == 3) { // Reverse the list

linkedList.reverse(); // Reverse the linked list

} else if (choice == 4) { // Exit

System.out.println("Exiting...");

break; // Exit the loop

} else {

System.out.println("Invalid choice, try again."); // Handle invalid input } }

scanner.close(); // Close the scanner

}
Variable Listing:

1. Node Class:
o data:
 Type: int
 Purpose: Holds the value of the node.
o next:
 Type: Node
 Purpose: Points to the next node in the linked list.
2. SimpleLinkedList Class:
o head:
 Type: Node
 Purpose: Points to the first node in the linked list.
3. Main Method:
o linkedList:
 Type: SimpleLinkedList
 Purpose: Instance to perform operations on the linked list.
o scanner:
 Type: Scanner
 Purpose: Reads user input.
o choice:
 Type: int
 Purpose: Stores the user's menu selection.
o value:
 Type: int
 Purpose: Stores the value entered by the user to be added to the linked list.
o previous:
 Type: Node
 Purpose: Points to the previous node while reversing the list.
o current:
 Type: Node
 Purpose: Points to the current node while traversing the list.
o next:
 Type: Node
 Purpose: Stores the next node while reversing the list.
34.Write a program in java to converts infix
arithmetic expressions to postfix

Algorithm

1. Initialize Stack and Output:


o Initialize an empty stack to hold operators.
o Initialize an empty string for the postfix output.
2. Parse Each Character in Infix Expression:
o For each character ch in the input string:
 If ch is an operand (a letter or number), add it directly to the output.
 If ch is an operator (+, -, *, /):
 Pop operators from the stack to the output until the stack is
empty or an operator with lower precedence is encountered.
 Push ch onto the stack.
 If ch is a left parenthesis (:
 Push it onto the stack.
 If ch is a right parenthesis ):
 Pop operators from the stack to the output until a left
parenthesis ( is encountered.
 Discard the left parenthesis.
3. Pop Remaining Operators:
o After reading all characters in the input, pop any remaining operators in the
stack to the output.
4. Return the Output String:
o The resulting string is the postfix notation of the input infix expression.
import java.io.*; // for I/O

class StackX
{
private int maxSize;
private char[] stackArray;
private int top;
//--------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
//--------------------------------------------------------------
public void push(char j) // put item on top of stack
{ stackArray[++top] = j; }
//--------------------------------------------------------------
public char pop() // take item from top of stack
{ return stackArray[top--]; }
//--------------------------------------------------------------
public char peek() // peek at top of stack
{ return stackArray[top]; }
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{ return (top == -1); }
//-------------------------------------------------------------
public int size() // return size
{ return top+1; }
//--------------------------------------------------------------
public char peekN(int n) // return item at index n
{ return stackArray[n]; }
//--------------------------------------------------------------
public void displayStack(String s)
{
System.out.print(s);
System.out.print("Stack (bottom-->top): ");
for(int j=0; j<size(); j++)
{
System.out.print( peekN(j) );
System.out.print(' ');
}
System.out.println("");
}
//--------------------------------------------------------------
} // end class StackX

class InToPost // infix to postfix conversion


{
private StackX theStack;
private String input;
private String output = "";
//--------------------------------------------------------------
public InToPost(String in) // constructor
{
input = in;
int stackSize = input.length();
theStack = new StackX(stackSize);
}
//--------------------------------------------------------------
public String doTrans() // do translation to postfix
{
for(int j=0; j<input.length(); j++) // for each char
{
char ch = input.charAt(j); // get it
theStack.displayStack("For "+ch+" "); // *diagnostic*
switch(ch)
{
case '+': // it's + or -
case '-':
gotOper(ch, 1); // go pop operators
break; // (precedence 1)
case '*': // it's * or /
case '/':
gotOper(ch, 2); // go pop operators
break; // (precedence 2)
case '(': // it's a left paren
theStack.push(ch); // push it
break;
case ')': // it's a right paren
gotParen(ch); // go pop operators
break;
default: // must be an operand
output = output + ch; // write it to output
break;
} // end switch
} // end for
while( !theStack.isEmpty() ) // pop remaining opers
{
theStack.displayStack("While "); // *diagnostic*
output = output + theStack.pop(); // write to output
}
theStack.displayStack("End "); // *diagnostic*
return output; // return postfix
} // end doTrans()
//--------------------------------------------------------------

public void gotOper(char opThis, int prec1)


{ // got operator from input
while( !theStack.isEmpty() )
{
char opTop = theStack.pop();
if( opTop == '(' ) // if it's a '('
{
theStack.push(opTop); // restore '('
break;
}
else // it's an operator
{
int prec2; // precedence of new op

if(opTop=='+' || opTop=='-') // find new op prec


prec2 = 1;
else
prec2 = 2;
if(prec2 < prec1) // if prec of new op less
{ // than prec of old
theStack.push(opTop); // save newly-popped op
break;
}
else // prec of new not less
output = output + opTop; // than prec of old
} // end else (it's an operator)
} // end while
theStack.push(opThis); // push new operator
} // end gotOp()
//--------------------------------------------------------------
public void gotParen(char ch)
{ // got right paren from input
while( !theStack.isEmpty() )
{
char chx = theStack.pop();
if( chx == '(' ) // if popped '('
break; // we're done
else // if popped operator
output = output + chx; // output it
} // end while
} // end popOps()
//--------------------------------------------------------------
} // end class InToPost

class InfixApp
{
public static void main(String[] args) throws IOException
{
String input, output;
while(true)
{
System.out.print("Enter infix: ");
System.out.flush();
input = getString(); // read a string from kbd
if( input.equals("") ) // quit if [Enter]
break;
// make a translator
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans(); // do the translation
System.out.println("Postfix is " + output + '\n');
} // end while
} // end main()
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
} // end class InfixApp
Here's a suitable algorithm and variable listing for this infix-to-postfix conversion program.

---

### Algorithm

1. **Initialize Stack and Output**:

- Initialize an empty stack to hold operators.

- Initialize an empty string for the postfix output.

2. **Parse Each Character in Infix Expression**:

- For each character `ch` in the input string:

- **If `ch` is an operand** (a letter or number), add it directly to the output.

- **If `ch` is an operator** (`+`, `-`, `*`, `/`):

- Pop operators from the stack to the output until the stack is empty or an operator with lower
precedence is encountered.

- Push `ch` onto the stack.

- **If `ch` is a left parenthesis** `(`:

- Push it onto the stack.

- **If `ch` is a right parenthesis** `)`:

- Pop operators from the stack to the output until a left parenthesis `(` is encountered.

- Discard the left parenthesis.

3. **Pop Remaining Operators**:

- After reading all characters in the input, pop any remaining operators in the stack to the output.

4. **Return the Output String**:

- The resulting string is the postfix notation of the input infix expression.
---

Variable Type Description


input String The infix expression to be converted to postfix.
output String The resulting postfix expression.
theStack StackX Custom stack for storing operators during conversion.
top int Index of the top of the stack in StackX.
maxSize int Maximum size of the stack (based on the length of input).
stackArray char[] Array to store stack elements in StackX.
prec1 int Precedence of the current operator.
prec2 int Precedence of operators already in the stack.
ch char Current character being processed in input.
opThis char Operator from the input currently being processed.
opTop char Operator popped from the stack during precedence checking.
chx char Character popped from the stack during parenthesis handling.
35 write a program to implement queue using link list
Algorithm

1. Link Class:
o Define Link with data dData and a pointer next to the next link.
o Initialize dData via constructor and set next to null.
o Display dData using displayLink().
2. FirstLastList Class:
o Initialize an empty list with first and last pointers set to null.
o isEmpty:
 Return true if first is null (indicating the list is empty).
o insertLast:
 Create a new link with the specified data.
 If the list is empty, set first to the new link.
 Otherwise, set last.next to the new link.
 Update last to point to the new link.
o deleteFirst:
 If the list is not empty, save dData from first.
 If first.next is null, set last to null.
 Move first to first.next and return the saved dData.
o displayList:
 Traverse the list from first to last.
 Display each link's data using displayLink().
3. LinkQueue Class:
o Initialize theList as a new FirstLastList.
o isEmpty:
 Return true if theList is empty.
o insert:
 Call insertLast() on theList to enqueue data at the rear.
o remove:
 Call deleteFirst() on theList to dequeue data from the front and
return it.
o displayQueue:
 Print "Queue (front-->rear):" and call displayList() on theList.
4. LinkQueueApp Class (Main):
o Create a new LinkQueue.
o Insert 20 and 40 into the queue and display the queue.
o Insert 60 and 80 into the queue and display the queue.
o Remove two items from the queue and display the queue.
. import java.io.*; // for I/O

class Link
{
public double dData; // data item
public Link next; // next link in list
// -------------------------------------------------------------
public Link(double d) // constructor
{ dData = d; }
// -------------------------------------------------------------
public void displayLink() // display this link
{ System.out.print(dData + " "); }
// -------------------------------------------------------------
} // end class Link

class FirstLastList
{
private Link first; // ref to first item
private Link last; // ref to last item
// -------------------------------------------------------------
public FirstLastList() // constructor
{
first = null; // no items on list yet
last = null;
}
// -------------------------------------------------------------
public boolean isEmpty() // true if no links
{ return first==null; }
// -------------------------------------------------------------
public void insertLast(double dd) // insert at end of list
{
Link newLink = new Link(dd); // make new link
if( isEmpty() ) // if empty list,
first = newLink; // first --> newLink
else
last.next = newLink; // old last --> newLink
last = newLink; // newLink <-- last
}
// -------------------------------------------------------------
public double deleteFirst() // delete first link
{ // (assumes non-empty list)
double temp = first.dData;
if(first.next == null) // if only one item
last = null; // null <-- last
first = first.next; // first --> old next
return temp;
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; // start at beginning
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");
}
// -------------------------------------------------------------
} // end class FirstLastList

class LinkQueue
{
private FirstLastList theList;
//--------------------------------------------------------------
public LinkQueue() // constructor
{ theList = new FirstLastList(); } // make a 2-ended list
//--------------------------------------------------------------
public boolean isEmpty() // true if queue is empty
{ return theList.isEmpty(); }
//--------------------------------------------------------------
public void insert(double j) // insert, rear of queue
{ theList.insertLast(j); }
//--------------------------------------------------------------
public double remove() // remove, front of queue
{ return theList.deleteFirst(); }
//--------------------------------------------------------------
public void displayQueue()
{
System.out.print("Queue (front-->rear): ");
theList.displayList();
}
//--------------------------------------------------------------
} // end class LinkQueue

class LinkQueueApp
{
public static void main(String[] args) throws IOException
{
LinkQueue theQueue = new LinkQueue();
theQueue.insert(20); // insert items
theQueue.insert(40);

theQueue.displayQueue(); // display queue

theQueue.insert(60); // insert items


theQueue.insert(80);

theQueue.displayQueue(); // display queue


theQueue.remove(); // remove items
theQueue.remove();

theQueue.displayQueue(); // display queue


} // end main()
} // end class LinkQueueApp
Explanation of Output:

1. First Display: After enqueuing 20 and 40, the queue shows these elements.
2. Second Display: After adding 60 and 80, the queue has 20 40 60 80.
3. Final Display: After dequeuing the first two elements (20 and 40), only 60 and 80
remain.
Type Description

Variable
dData double Stores data in each link (node) of the linked list.
next Link Points to the next link in the linked list.
first Link Points to the first link in the FirstLastList.
last Link Points to the last link in the FirstLastList.
theList FirstLastList An instance of FirstLastList to represent the queue.
temp double Holds the data of the deleted link in deleteFirst.
current Link Used for traversing and displaying all elements in the list.
theQueue LinkQueue Represents the queue instance in LinkQueueApp.
36 Write a program to implement link using stack

Algorithm

1. Initialize the Stack:


o Create a new instance of LinkStack:
 Initialize theList as a LinkList, which is initially empty.
2. Push Operation:
o To push an item onto the stack:
 Create a new Link object with the data to be added ( dData).
 Set newLink.next to the current first link in theList.
 Set first to newLink to mark it as the new top of the stack.
3. Pop Operation:
o To pop an item from the stack:
 Check if theList is empty by calling isEmpty().
 If isEmpty returns true, the stack is empty; do not proceed
with popping.
 Otherwise:
 Save the data from first (top link) in a temporary variable
(temp.dData).
 Update first to first.next, effectively removing the top
link.
 Return the saved data.
4. Display Stack:
o To display the stack:
 Start from first in theList.
 Traverse through each link:
 Print the dData of the current link.
 Move to the next link by setting current to current.next.
 Continue until current becomes null (end of list).
5. LinkStackApp (Main):
o Create a new instance of LinkStack.
o Perform a sequence of operations to demonstrate stack functionality:
 Push 20 and 40 onto the stack.
 Display the stack to show 40 at the top, followed by 20.
 Push 60 and 80 onto the stack.
 Display the stack to show 80, 60, 40, and 20.
 Pop the top two items (80 and 60) from the stack.
 Display the stack to show the remaining elements ( 40 and 20).
import java.io.*; // for I/O
class Link
{
public double dData; // data item
public Link next; // next link in list
// -------------------------------------------------------------
public Link(double dd) // constructor
{ dData = dd; }
// -------------------------------------------------------------
public void displayLink() // display ourself
{ System.out.print(dData + " "); }
} // end class Link

class LinkList
{
private Link first; // ref to first item on list
// -------------------------------------------------------------
public LinkList() // constructor
{ first = null; } // no items on list yet
// -------------------------------------------------------------
public boolean isEmpty() // true if list is empty
{ return (first==null); }
// -------------------------------------------------------------
public void insertFirst(double dd) // insert at start of list
{ // make new link
Link newLink = new Link(dd);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public double deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first-->old next
return temp.dData; // return deleted link
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; // start at beginning of list
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");
}
// -------------------------------------------------------------
} // end class LinkList
class LinkStack
{
private LinkList theList;
//--------------------------------------------------------------
public LinkStack() // constructor
{
theList = new LinkList();
}
//--------------------------------------------------------------
public void push(double j) // put item on top of stack
{
theList.insertFirst(j);
}
//--------------------------------------------------------------
public double pop() // take item from top of stack
{
return theList.deleteFirst();
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return ( theList.isEmpty() );
}
//--------------------------------------------------------------
public void displayStack()
{
System.out.print("Stack (top-->bottom): ");
theList.displayList();
}
//--------------------------------------------------------------
} // end class LinkStack

class LinkStackApp
{
public static void main(String[] args) throws IOException
{
LinkStack theStack = new LinkStack(); // make stack

theStack.push(20); // push items


theStack.push(40);

theStack.displayStack(); // display stack

theStack.push(60); // push items


theStack.push(80);

theStack.displayStack(); // display stack

theStack.pop(); // pop items


theStack.pop();

theStack.displayStack(); // display stack


} // end main()
} // end class LinkStackApp
Variable Listing

Variable Type Description

dData double Data held by each link in the stack.

next Link Points to the next link in the stack.

first Link Points to the top element in LinkList.

theList LinkList Represents the linked list in LinkStack.

theStack LinkStack Stack instance in LinkStackApp.

temp Link Temporary variable in deleteFirst for saving the top link.

current Link Traverses the list in displayList to print each link’s data.
Explanation of Output

1. First Display: After pushing 20 and 40, the stack shows these elements from top to
bottom as 40 20.
2. Second Display: After pushing 60 and 80, the stack shows 80 60 40 20.
3. Final Display: After popping two elements (80 and 60), the stack shows 60 40 20.

This code efficiently implements a stack using linked lists and demonstrates the core stack
operations: push, pop, and display.

You might also like