Mercurial > hg > Members > kazuma > jungle-ormapper
view src/main/java/jp/ac/u_ryukyu/ie/cr/jungle/data/list/List.java @ 0:44465893e8b8
first Commit
author | Kazuma |
---|---|
date | Wed, 30 Nov 2016 01:47:55 +0900 |
parents | |
children |
line wrap: on
line source
package jp.ac.u_ryukyu.ie.cr.jungle.data.list; import java.util.Iterator; import java.util.Stack; public class List<T> implements Iterable<T> { final private Node<T> head; public List() { this.head = new headNode<>(); } @SafeVarargs public List(T... attributes) { List<T> list = new List<>(); for (T attribute : attributes) { list = list.addLast(attribute); } this.head = list.getHead(); } private List(Node<T> head) { this.head = head; } public Node<T> getHead() { return head; } public List<T> add(int num, T attribute) { Node<T> newHead = head.add(0, num, attribute); if (newHead == null) return this; return new List<>(newHead); } public List<T> addLast(T attribute) { Node<T> newHead = head.addLast(attribute); return new List<>(newHead); } public T index(int num) { int count = 0; Node<T> currentNode = head.getNext(); while (currentNode != null) { if (count == num) return currentNode.getAttribute(); currentNode = currentNode.getNext(); count++; } return null; } public Iterator<T> iterator() { return new Iterator<T>() { Node<T> currentNode = head.getNext(); @Override public boolean hasNext() { return currentNode.getAttribute() != null; } @Override public T next() { T attribute = currentNode.getAttribute(); currentNode = currentNode.getNext(); return attribute; } }; } public Iterator<T> reverseIterator() { Node<T> currentNode = head.getNext(); Stack<T> stack = new Stack<>(); while (currentNode.getAttribute() != null) { stack.push(currentNode.getAttribute()); currentNode = currentNode.getNext(); } return new Iterator<T>() { @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { return stack.pop(); } }; } public List<T> delete(int num) { Node<T> newNode = head.delete(0, num); if (newNode == null) return this; return new List<>(newNode); } public List<T> replace(int num, T attribute) { Node<T> newHead = head.replaceNode(0, num, attribute); if (newHead == null) return this; return new List<>(newHead); } public T tail() { return index(length() - 1); } public T head() { return index(0); } public List<T> deleteLast() { return delete(head.length() - 1); } public List<T> deleteHead() { return delete(0); } public int length() { return head.length(); } @Override public String toString() { String pathString = "<"; Iterator<T> iterator = reverseIterator(); while (true) { pathString += iterator.next(); if (iterator.hasNext()) pathString += ","; else break; } pathString += ">"; return pathString; } public List<T> append(List<T> list) { Iterator<T> iterator = list.iterator(); List<T> newList = this; while (iterator.hasNext()) { T attribute = iterator.next(); newList = newList.addLast(attribute); } return newList; } }