Implement a generic LinkedList<E> with add, get, size, contains and Iterable support, and use it with Strings and Integers.
Solution
Main.java
import java.util.Iterator;
import java.util.NoSuchElementException;
class MyList<E> implements Iterable<E> {
private static class Node<E> {
final E value;
Node<E> next;
Node(E v) { value = v; }
}
private Node<E> head, tail;
private int size;
void add(E e) {
Node<E> n = new Node<>(e);
if (head == null) head = tail = n; else { tail.next = n; tail = n; }
size++;
}
E get(int index) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException("index " + index);
Node<E> cur = head;
for (int i = 0; i < index; i++) cur = cur.next;
return cur.value;
}
boolean contains(E e) { for (E x : this) if (x.equals(e)) return true; return false; }
int size() { return size; }
public Iterator<E> iterator() {
return new Iterator<>() {
private Node<E> cur = head;
public boolean hasNext() { return cur != null; }
public E next() {
if (cur == null) throw new NoSuchElementException();
E v = cur.value; cur = cur.next; return v;
}
};
}
}
public class Main {
public static void main(String[] args) {
MyList<String> langs = new MyList<>();
langs.add("Java"); langs.add("Kotlin"); langs.add("Scala");
StringBuilder sb = new StringBuilder();
for (String s : langs) sb.append(s.charAt(0));
System.out.println(sb + " " + langs.get(1) + " " + langs.contains("Go") + " " + langs.size());
MyList<Integer> nums = new MyList<>();
for (int i = 1; i <= 5; i++) nums.add(i * i);
int sum = 0;
for (int n : nums) sum += n;
System.out.println(sum + " " + nums.get(4));
}
}
Output Verified by compiling and running
JKS Kotlin false 3
55 25
One generic implementation serves every element type with full compile-time checking, and Iterable makes it work in for-each loops.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!