Lab 04 Data Structures
Lab 04 Data Structures
1. Stack using array: Understand provided code and implement all required
methods in Stack. Stack Code is given below:
class Stack
{
private int arr[];
private int top;
private int capacity;
2. Stack using Linked list: Understand provided code and implement all required
methods in Stack. Stack Code is given below:
class Stack
{
private Node top;
public Stack() {
this.top = null;
}
class StackImpl
{
public static void main(String[] args)
{
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
stack.pop();
stack.pop();
if (stack.isEmpty()) {
System.out.print("Stack is empty");
} else {
System.out.print("Stack is not empty");
}
}
}
After implementing all the methods, run the code. Your output should be like as follows:
3: Queue using array: Understand provided code and implement all required
methods in Queue. Queue Code is given below:
// Class for queue
class Queue
{
private int arr[];
private int front;
private int rear;
private int capacity;
private int count;
class Main
{
// main function
public static void main (String[] args)
{
// create a queue of capacity 5
Queue q = new Queue(5);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
if (q.isEmpty())
System.out.println("Queue Is Empty");
else
System.out.println("Queue Is Not Empty");
}
}
After implementing all the methods, run the code. Your output should be like as follows:
4. Queue using Linked list: Understand provided code and implement all required
methods in Queue. Queue Code is given below:
// A linked list node
class Node
{
int data; // integer data
Node next; // pointer to the next node
class Queue
{
private static Node rear = null, front = null;
// Utility function to remove front element from the queue
and check for Queue Underflow
public static int dequeue() // delete at the beginning
{
// Write your code here
}
class Main {
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
if (q.isEmpty()) {
System.out.print("Queue is empty");
} else {
System.out.print("Queue is not empty");
}
}
}
After implementing all the methods, run the code. Your output should be like as follows:
5. Queue using two Stacks: Understand provided code and implement all
required methods in Queue Class. Sample Code is given below:
// Implement Queue using two stacks
class Queue {
private Stack s1, s2;
// Constructor
Queue() {
s1 = new Stack();
s2 = new Stack();
}
System.out.println(q.dequeue()); // print 1
System.out.println(q.dequeue()); // print 2
}
}
6. Think about the inverse of task 05 (Stack using queue) and implement all the
required methods.