본문 바로가기

미국유학/Data Structure and Algorithm

Iterable, Linkedlist, Queues, Stack, Trees

public class LibraryCatalog implements Iterable<Book> {
    private ArrayList<Book> books;

    LibraryCatalog() {
        books = new ArrayList<>();
    }

    public void addBook(String name, String author) {
        Book book = new Book(name, author);
        books.add(book);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < books.size(); i++) {
            sb.append(books.get(i));
            sb.append(System.lineSeparator());
        }
        return sb.toString();
    }


    @Override
    public Iterator<Book> iterator() {
        return books.iterator();
    }
}

 

public class LibraryCatalogExample {
    public static void main(String[] args) {
        LibraryCatalog catalog = new LibraryCatalog();
        catalog.addBook("The Women", "Kristin Hannah");
        catalog.addBook("The Ministry of Time", "Kaliane Bradley");
        catalog.addBook("X",  "Sue Grafton");

        Iterator<Book> it = catalog.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        System.out.println();

        // Another way to iterate over books in the catalog - can do it because LibraryCatalog implements Iterable
        for (Book book: catalog) {
            System.out.println(book);
        }
    }
}

 

package linkedlists;

import java.util.Iterator;

/** A class representing a singly linked list. */
public class LinkedList  implements  Iterable<Node> {
    private Node head, tail;

    /** Constructor */
    public LinkedList() {
       head = null;
       tail = null;
    }

    /**
     * Creates a new node with the given element and adds it to the back of the
     * list
     */
    public void append(int elem) {
       Node newNode = new Node(elem);
       if (tail != null) {
          tail.setNext(newNode);
          tail = newNode;
       } else { // if it's an empty list
          head = tail = newNode;
       }
    }

    /** Prints all the nodes in the link list */
    public void printNodes() {
       Node current = head;
       while (current != null) {
          System.out.print(current.getElem() + " ");
          current = current.next();
       }
       System.out.println();
    }

    /**
     * Insert a new node with the given element in front of the linked list
     * @param elem element
     */
    public void insertAtFront(int elem) {
       // Insert a new node with elem in front of the linked list
       Node newNode = new Node(elem);
       if (head == null) {
          head = tail = newNode;
       }
       else {
          newNode.setNext(head);
          head = newNode;
       }
    }

    /**
     * Insert a new node with the given element at index i
     * @param i index
     * @param elem element
     */
    public void insertAtIndex(int i, int elem) {
       // Iinsert a new node with the given elem
       // at "index" i
       // Example:
       // If the linked list is 5 -> 7 - > 2 and we call
       // insertAtIndex(1, 8), the linked list will be
       // 5 -> 8 -> 7 -> 2  we inserted element 8 at "index" = 1.

       if (head == null)
          return; // nothing to do
       if (i == 0) {
          insertAtFront(elem);
       }
       else {
          Node current = head;
          int count = 0;
          while (current != null && count < i - 1) {
             current = current.next();
             count+= 1;
          }
          if (current == null)
             return; // no such index
          Node newNode = new Node(elem);
          if (current == tail)
             tail = newNode;
          newNode.setNext(current.next());
          current.setNext(newNode);
       }

    }

    /** Remove a node after the prevNode
     *
     * @param prevNode node before the one we need to remove
     */
    public void removeNodeAfter(Node prevNode) {
       if (head == null || prevNode == null || prevNode.next() == null)
          return; // nothing to do since no node after prevNode

       if (prevNode.next() == tail)
          tail = prevNode;
       prevNode.setNext(prevNode.next().next());
    }

    /** Get the element at the node at "index" k from the end of the list
     *
     * @param k index from the end of the linked list
     * @return element at that index
     */
    public int getNodeAtIndexKFromEnd(int k) {
       Node slow = head;
       Node fast = head;
       int count = 0;
       while (fast != null && count < k) {
          fast = fast.next();
          count++;
       }
       if (fast == null) {
          System.out.println("No such index");
          return Integer.MAX_VALUE;
       }

       while (fast != tail) {
          slow = slow.next();
          fast = fast.next();
       }

       return slow.getElem();
    }


    /**
     * Return the head of the linked list
     * @return head
     */
    public Node head() {
       return head;
    }

    /** Returns the tail
     *
     * @return tail
     */
    public Node tail() {
       // Useful for testing
       return tail;
    }

    @Override
    public Iterator<Node> iterator() {
       return new MyLinkedListIterator();
    }

    // An inner class implementing Iterator
    public class MyLinkedListIterator implements Iterator<Node> {
       private Node current;

       public MyLinkedListIterator() {
          current = head;
       }

       @Override
       public boolean hasNext() {
          return current != null;
       }

       @Override
       public Node next() {
          Node nextNode = current;
          current = current.next();
          return nextNode;
       }
    }

}

 

package queues;
/** A class that implements a Queue ADT using a circular array
 *  The code is modified from Prof. Galles's code.
 */
public class ArrayQueue implements Queue {

    private Object data[]; // the array that will store the queue
    private int head;
    private int tail;
    private int size; // the maximum # of elements it can hold

    public ArrayQueue(int maxsize) {
       data = new Object[maxsize];
       head = 0;
       tail = 0;
       size = maxsize;
    }

    /** Add an element to the end of the queue, if it's not full */
    public void enqueue(Object elem) {
       // Before adding, check if the queue is full
       if ((tail + 1) % size == head) {
          System.out.println("Queue is full: Can't add an element");
          return;
       }
       data[tail] = elem;
       tail = (tail + 1) % size;
    }

    /**
     * Dequeues the element from the queue
     * @return element that was dequeued
     */
    public Object dequeue() {
       Object retval;

       // Check if the queue is empty
       if (empty()) {
          System.out.println("Queue is empty");
          return null;
       }
       retval = data[head];
       head = (head + 1) % size;
       return retval;
    }

    public boolean empty() {
       return head == tail;
    }

    public String toString() {
       String result = "[";
       int tmpHead = head;
       if (tmpHead != tail) {
          result = result + data[tmpHead];
          tmpHead = (tmpHead + 1) % size;
          while (tmpHead != tail) {
             result = result + "," + data[tmpHead];
             tmpHead = (tmpHead + 1) % size;
          }
       }
       result = result + "]";
       return result;
    }

}

 

package queues;
/** Implementation of Queue ADT using a singly linked list. 
 *  This implementation does not use a dummy node. */
public class ListQueue implements Queue {
    private Node head;
    private Node tail;

    ListQueue() {
       head = null;
       tail = null;
    }

    /**
     * Create a new node with elem and add it to the
     * end of the linked list
     * @param elem element to add to the queue
     */
    public void enqueue(Object elem) {
       if (head == null) {
          head = new Node(elem);
          tail = head;
       } else {
          tail.setNext(new Node(elem));
          tail = tail.next();
       }
    }

    /**
     * Remove the first element from the queue
     * (and return its value)
     * @return the first element in the queue
     */
    public Object dequeue() {
       Object dequeuedElem;

       //if (head == null)
       // return null;
       if (empty()) {
          System.out.println("No elements in the queue");
          return null;
       }
       dequeuedElem = head.getElem();
       head = head.next();
       if (head == null)
          tail = null;
       return dequeuedElem;
    }

    /** Return true if the queue has no elements */
    public boolean empty() {
       return (head == null);
    }

    /** Return a string represeting a queue */
    public String toString() {
       String result = "[";
       Node tmp = head;
       if (tmp != null) {
          result = result + tmp.getElem();
          tmp = tmp.next();
          while (tmp != null) {
             result = result + "," + tmp.getElem();
             tmp = tmp.next();
          }
       }
       result = result + "]";
       return result;
    }

}

 

 

'미국유학 > Data Structure and Algorithm' 카테고리의 다른 글

2.11 DSA  (0) 2025.02.12
linkedlist - reverse  (0) 2025.02.11
QueueWithTwoStacks  (0) 2025.02.09
Binary Search Tree (BSTNode)  (0) 2025.02.09
2월6일 DSA  (0) 2025.02.07