P1-P5: rewrite to match current syllabus
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
98
P1.java
98
P1.java
@@ -1,8 +1,92 @@
|
||||
class P1 {
|
||||
public static void main(String[] _args) {
|
||||
int a = 44;
|
||||
int b = 56;
|
||||
class Stack {
|
||||
private int[] array;
|
||||
private int top;
|
||||
|
||||
public Stack(int capacity) {
|
||||
array = new int[capacity];
|
||||
top = -1;
|
||||
}
|
||||
|
||||
public void push(int item) {
|
||||
if (top == array.length - 1) {
|
||||
System.out.println("Stack Overflow");
|
||||
} else {
|
||||
array[++top] = item;
|
||||
System.out.println("Pushed " + item + " to the stack");
|
||||
}
|
||||
}
|
||||
|
||||
public int pop() {
|
||||
if (top == -1) {
|
||||
System.out.println("Stack Underflow");
|
||||
return -1;
|
||||
} else {
|
||||
int item = array[top--];
|
||||
System.out.println("Popped " + item + " from the stack");
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return top == -1;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(a + " + " + b + " = " + (a + b));
|
||||
}
|
||||
}
|
||||
class Queue {
|
||||
private int[] array;
|
||||
private int front;
|
||||
private int rear;
|
||||
private int size;
|
||||
|
||||
public Queue(int capacity) {
|
||||
array = new int[capacity];
|
||||
front = 0;
|
||||
rear = -1;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
public void enqueue(int item) {
|
||||
if (size == array.length) {
|
||||
System.out.println("Queue is full");
|
||||
} else {
|
||||
rear = (rear + 1) % array.length;
|
||||
array[rear] = item;
|
||||
size++;
|
||||
System.out.println("Enqueued " + item + " to the queue");
|
||||
}
|
||||
}
|
||||
|
||||
public int dequeue() {
|
||||
if (size == 0) {
|
||||
System.out.println("Queue is empty");
|
||||
return -1;
|
||||
} else {
|
||||
int item = array[front];
|
||||
front = (front + 1) % array.length;
|
||||
size--;
|
||||
System.out.println("Dequeued " + item + " from the queue");
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return size == 0;
|
||||
}
|
||||
}
|
||||
|
||||
public class P1 {
|
||||
public static void main(String[] args) {
|
||||
Stack stack = new Stack(5);
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.pop();
|
||||
stack.pop();
|
||||
stack.pop();
|
||||
|
||||
Queue queue = new Queue(5);
|
||||
queue.enqueue(1);
|
||||
queue.enqueue(-4);
|
||||
queue.dequeue();
|
||||
queue.dequeue();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user