Untitled
unknown
plain_text
7 months ago
2.8 kB
5
Indexable
Never
Week 3 ---------------------------------------- import java.util.Stack; class StackOfIntegers { private Stack<Integer> stack; public StackOfIntegers() { stack = new Stack<>(); } public void push(int value) { stack.push(value); } public int pop() { return stack.pop(); } public void displayFromTop() { System.out.println("Stack contents from top to bottom: " + stack); } public void displayFromBot() { Stack<Integer> temp = new Stack<>(); while (!stack.isEmpty()) { temp.push(stack.pop()); } System.out.println("Stack contents from bottom to top: " + temp); while (!temp.isEmpty()) { stack.push(temp.pop()); } } public int stackTop() { return stack.peek(); } public boolean isEmpty() { return stack.isEmpty(); } public boolean isFull() { // Stack does not have a fixed size, so it is not possible to determine if it is full return false; } } Week 3 q2 ------------------------------------------------------- public class IntegerLinkedList { private Node head; private static class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } public boolean isEmpty() { return head == null; } public void display() { if (isEmpty()) { System.out.println("List is empty."); return; } Node current = head; while (current != null) { System.out.print(current.data + " -> "); current = current.next; } System.out.println("null"); } public void addAtLast(int value) { Node newNode = new Node(value); if (isEmpty()) { head = newNode; return; } Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } public void deleteAtHead() { if (isEmpty()) { throw new RuntimeException("List is empty. Cannot delete head."); } head = head.next; } public static void main(String[] args) { IntegerLinkedList list = new IntegerLinkedList(); list.addAtLast(10); list.addAtLast(20); list.addAtLast(30); System.out.println("List after adding 10, 20, 30:"); list.display(); System.out.println("Deleting head of the list:"); list.deleteAtHead(); list.display(); System.out.println("Deleting head of the list:"); list.deleteAtHead(); list.display(); } }
Leave a Comment