Skip to content

Instantly share code, notes, and snippets.

@Sedose
Last active September 3, 2024 19:54
Show Gist options
  • Save Sedose/aed5b0495455484d0c0c09a3a68e0198 to your computer and use it in GitHub Desktop.
Save Sedose/aed5b0495455484d0c0c09a3a68e0198 to your computer and use it in GitHub Desktop.
Leetcode Single queue using 2 stacks.java. Using Java implicitly named classes. Just to show that we can do Java without explicitly named classes
import java.util.ArrayList;
import java.util.List;
void main() {
System.out.println("Hello, Java 22!");
QueueOperations queue = createQueue(createStack(), createStack());
queue.push(1);
queue.push(2);
queue.push(3);
queue.pop();
queue.peek();
queue.pop();
queue.pop();
queue.isNotEmpty();
System.out.println("The end!");
}
private QueueOperations createQueue(StackOperations stack1, StackOperations stack2) {
return new QueueOperations() {
public void push(int item) {
stack1.push(item);
}
public int pop() {
shiftStacks();
return stack2.pop();
}
public int peek() {
shiftStacks();
return stack2.peek();
}
public boolean isEmpty() {
return stack1.isEmpty() && stack2.isEmpty();
}
public boolean isNotEmpty() {
return stack1.isNotEmpty() || stack2.isNotEmpty();
}
private void shiftStacks() {
if (stack2.isEmpty()) {
while (stack1.isNotEmpty()) {
stack2.push(stack1.pop());
}
}
}
};
}
private StackOperations createStack() {
List<Integer> elements = new ArrayList<>();
return new StackOperations() {
public void push(int item) {
elements.add(item);
}
public int pop() {
return elements.removeLast();
}
public int peek() {
return elements.getLast();
}
public boolean isEmpty() {
return elements.isEmpty();
}
public boolean isNotEmpty() {
return !elements.isEmpty();
}
};
}
interface QueueOperations {
void push(int item);
int pop();
int peek();
boolean isEmpty();
boolean isNotEmpty();
}
interface StackOperations {
void push(int item);
int pop();
int peek();
boolean isEmpty();
boolean isNotEmpty();
}
@Sedose
Copy link
Author

Sedose commented Sep 3, 2024

Put it into newly created Main.java and run:
java --enable-preview --source 22 Main.java

@Sedose
Copy link
Author

Sedose commented Sep 3, 2024

@Sedose
Copy link
Author

Sedose commented Sep 3, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment