From 152e3895cbf1a85ff067b2c7f17d3e0c43f8e940 Mon Sep 17 00:00:00 2001 From: blank <blank@caltech.edu> Date: Sat, 21 Jan 2023 14:16:44 -0800 Subject: [PATCH] after lecture06 --- 06/ICollection.java | 22 ++++++++++++++ 06/LinkedList.java | 73 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 06/ICollection.java create mode 100644 06/LinkedList.java diff --git a/06/ICollection.java b/06/ICollection.java new file mode 100644 index 0000000..9797394 --- /dev/null +++ b/06/ICollection.java @@ -0,0 +1,22 @@ +import java.util.Iterator; + +public interface ICollection<E> extends Iterable<E> { + public void add(E e); + public void clear(); + + public Iterator<E> iterator(); + + default public boolean contains(E e) { + for (E item : this) { + if (e == null ? item == null : e.equals(item)) { + return true; + } + } + return false; + } + + public int size(); + default public boolean isEmpty() { + return this.size() == 0; + } +} \ No newline at end of file diff --git a/06/LinkedList.java b/06/LinkedList.java new file mode 100644 index 0000000..4dacb6b --- /dev/null +++ b/06/LinkedList.java @@ -0,0 +1,73 @@ +public class LinkedList<E> implements IList<E> { + private Node<E> head; + private int size; + + private static class Node<E> { + public final E data; + public Node<E> next; + + public Node(E data) { + this(data, null); + } + + public Node(E data, Node<E> next) { + this.data = data; + this.next = next; + } + } + + @Override + public int size() { + return this.size; + } + + @Override + public void set(int idx, E elem) { + if (idx >= this.size || idx < 0) { + throw new IllegalArgumentException(); + } + } + + @Override + public E get(int idx) { + return null; + } + + @Override + public void clear() { + this.head = null; + this.size = 0; + } + + @Override + public void add(int idx, E elem) { + if (idx > this.size || idx < 0) { + throw new IllegalArgumentException(); + } + } + + @Override + public void add(E elem) { + if (this.head == null) { + this.head = new Node<>(elem); + } + else { + // Write only the else in C16 + // I AM ABOUT TO WRITE CODE THAT DOESN'T WORK + // BEWARE!! + + /* + Node<E> curr = this.head; + while (curr.next != null) { + curr = curr.next; + } + curr.next = new Node<>(elem); + */ + Node<E> curr; + for (curr = this.head; curr.next != null; curr = curr.next) { + + } + } + this.size++; + } +} -- GitLab