Linked Lists
stacks and queues for linked lists
import java.util.LinkedList;
public class Cars {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Cars.main(null);
public class StackLinkedList<T> {
private Node<T> top;
private int size;
public StackLinkedList() {
this.top = null;
this.size = 0;
}
public boolean isEmpty() {
return top == null;
}
public int size() {
return size;
}
public void push(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
size++;
}
public T pop() {
if (isEmpty()) {
throw new NoSuchElementException("Stack is empty");
}
T data = top.data;
top = top.next;
size--;
return data;
}
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("Stack is empty");
}
return top.data;
}
private static class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
}
}