Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Created by Julio Tentor <jtentor@fi.unju.edu.ar>
- //
- import java.util.Iterator;
- public class SimpleLinkedListIterator<ELEMENT> implements Iterable<ELEMENT> {
- private class Node {
- public ELEMENT item;
- public Node next;
- public Node() {
- this(null, null);
- }
- public Node(ELEMENT item) {
- this(item, null);
- }
- public Node(ELEMENT item, Node next) {
- this.item = item;
- this.next = next;
- }
- @Override
- public String toString() {
- return this.item.toString();
- }
- }
- private Node head;
- private int count;
- private Node tail;
- public int size() {
- return this.count;
- }
- public SimpleLinkedListIterator() {
- this.head = null;
- this.count = 0;
- this.tail = null;
- }
- public void addFirst(ELEMENT item) {
- Node temp = new Node(item, this.head);
- if (this.count == 0) {
- this.tail = temp;
- }
- this.head = temp;
- ++this.count;
- }
- public void addLast(ELEMENT item) {
- Node temp = new Node(item, null);
- if (this.count == 0) {
- this.head = temp;
- } else {
- this.tail.next = temp;
- }
- this.tail = temp;
- ++this.count;
- }
- public ELEMENT removeFirst() {
- if (this.count == 0) {
- throw new RuntimeException("La lista está vacía...");
- }
- ELEMENT item = this.head.item;
- this.head = this.head.next;
- if (this.head == null) {
- this.tail = null;
- }
- --this.count;
- return item;
- }
- public ELEMENT removeLast() {
- if (this.count == 0) {
- throw new RuntimeException("La lista está vacía...");
- }
- ELEMENT item = this.tail.item;
- if (this.head.next == null) {
- this.head = this.tail = null;
- } else {
- Node skip = this.head;
- while (skip.next.next != null) {
- skip = skip.next;
- }
- this.tail = skip;
- this.tail.next = null;
- }
- --this.count;
- return item;
- }
- /*
- public void Mostrar() {
- for (Node skip = this.head; skip != null; skip = skip.next) {
- System.out.printf("%s ", skip.item.toString());
- }
- System.out.println();
- }
- */
- @Override
- public Iterator<ELEMENT> iterator() {
- return new MyIterator(this.head);
- }
- private class MyIterator implements Iterator<ELEMENT> {
- private Node current;
- public MyIterator(Node current) {
- this.current = current;
- }
- @Override
- public boolean hasNext() {
- return this.current != null;
- }
- @Override
- public ELEMENT next() {
- if (!this.hasNext()) {
- throw new RuntimeException("La lista está vacía...");
- }
- ELEMENT item = this.current.item;
- this.current = this.current.next;
- return item;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement