Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface MyIterator<T> {
- boolean hasNext();
- T next();
- }
- class MyLinkedList {
- private static class Node implements MyIterator<Node>{
- private int data;
- private Node next;
- public Node(int data) {
- this.data = data;
- }
- @Override
- public boolean hasNext() {
- return this.next != null;
- }
- @Override
- public Node next() {
- if(this.next == null) {
- throw new RuntimeException("no elements");
- }
- return this.next;
- }
- }
- private Node head = null;
- public void addAtFront(int element) {
- Node node = new Node(element);
- node.next = this.head;
- this.head = node;
- }
- public void addAtEnd(int element) {
- Node node = new Node(element);
- if (this.head == null) {
- this.head = node;
- } else {
- Node iterator = this.head;
- while (iterator.hasNext()) {
- iterator = iterator.next();
- }
- iterator.next = node;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement