comp project 2nd term
comp project 2nd term
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");
switch (choice) {
if (top == 4) {
top++;
stack[top] = value;
if (top == -1) {
System.out.println("Stack is empty.");
} else {
top--;
break;
if (top == -1) {
System.out.println("Stack is empty.");
} else {
break;
case 4: // Exit
System.out.println("Exiting...");
scanner.close();
return;
default:
}
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
System.out.println("Enter a number:");
if (value % 2 == 0) {
if (evenTop == 4) {
evenTop++;
evenStack[evenTop] = value;
if (oddTop == 4) {
oddTop++;
oddStack[oddTop] = value;
} } }
System.out.println("\nOdd Stack:");
if (oddTop == -1) {
} else {
for (int i = oddTop; i >= 0; i--) {
System.out.println(oddStack[i]);
System.out.println("\nEven Stack:");
if (evenTop == -1) {
} else {
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
import java.util.Stack;
stack1.push(value); }
stack2.push(value); }
while (!stack1.isEmpty()) {
mergedStack.push(stack1.pop()); }
while (!stack2.isEmpty()) {
mergedStack.push(stack2.pop()); }
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
int front = -1, rear = -1; // Pointers for front and rear of the queue
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("1. Enqueue");
System.out.println("2. Exit");
switch (choice) {
if (rear == queue.length - 1) {
} else {
rear++;
queue[rear] = value;
break;
case 2: // Exit
System.out.println("Exiting...");
scanner.close();
return;
default:
} }}
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
class Node {
// Constructor
Node(int data) {
this.data = data;
if (head == null) {
head = newNode; // If the list is empty, set the head to the new node
} else {
if (head == null) {
System.out.println("List is empty.");
return;
}
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("3. Exit");
linkedList.add(value); // Add the value to the list } else if (choice == 2) { // Display the list
System.out.println("Exiting...");
} else {
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
class Node {
// Constructor
Node(int data) {
this.data = data;
if (head == null) {
head = newNode; // If the list is empty, set the head to the new node
} else {
// Method to find and display the largest element in the linked list
System.out.println("List is empty.");
return;
int largest = head.data; // Start with the first element as the largest
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("3. Exit");
System.out.println("Exiting...");
} else {
}
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;
class Node {
// Constructor
Node(int data) {
this.data = data;
if (head == null) {
head = newNode; // If the list is empty, set the head to the new node
} else {
if (head == null) {
System.out.println("List is empty.");
return;
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("4. Exit");
System.out.println("Exiting...");
} else {
}
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
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 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
- Pop operators from the stack to the output until the stack is empty or an operator with lower
precedence is encountered.
- Pop operators from the stack to the output until a left parenthesis `(` is encountered.
- After reading all characters in the input, pop any remaining operators in the stack to the output.
- The resulting string is the postfix notation of the input infix expression.
---
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);
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
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
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.