Lab DSA
Lab DSA
1.stack
import java.util.Scanner;
class Stack {
int stack[] = new int[5]; // Stack size is 5
int top = -1;
do {
System.out.println("\n1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter data to push: ");
data = sc.nextInt();
s.push(data);
break;
case 2:
s.pop();
break;
case 3:
s.peek();
break;
case 4:
System.out.println("Exiting...");
s.displayStack(); // Display the stack contents before exit
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 4);
sc.close();
}
}
Output:
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 1
Enter data to push: 10
10 pushed into the stack.
Current stack: 10
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 1
Enter data to push: 20
20 pushed into the stack.
Current stack: 10 20
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 3
Top element is 20
Current stack: 10 20
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 2
20 popped from the stack.
Current stack: 10
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 4
Exiting...
Current stack: 10
2.Queue
Import java.util.Scanner;
Class Queue {
Int queue[] = new int[5]; // Queue size is 5
Int front = -1;
Int rear = -1;
Do {
System.out.println(“\n1. Enqueue”);
System.out.println(“2. Dequeue”);
System.out.println(“3. Peek”);
System.out.println(“4. Exit”);
System.out.print(“Enter your choice: “);
Choice = sc.nextInt();
Switch (choice) {
Case 1:
System.out.print(“Enter data to enqueue: “);
Data = sc.nextInt();
q.enqueue(data);
break;
case 2:
q.dequeue();
break;
case 3:
q.peek();
break;
case 4:
System.out.println(“Exiting…”);
q.displayQueue(); // Display the queue contents before exit
break;
default:
System.out.println(“Invalid choice!”);
}
} while (choice != 4);
Sc.close();
}
}
Sample Input/Output:
1. Enqueue
2. Dequeue
3. Peek
4. Exit
Enter your choice: 1
Enter data to enqueue: 10
10 enqueued into the queue.
Current queue: 10