// ----------------------------------------------------------------
// Autor: Sylwester Łuczak
//        sylwester.luczak@gmail.com
//        www.sylwester-luczak.pl
// ----------------------------------------------------------------
// O programie:
//		  Program zawiera klasę List, bedącą implementacją listy
//		  jednokierunkowej.

package tools;

public class OneWayList {
	protected class Node {
		// Constructor: sets the pointer to null value
		public Node() {
			next = null;
		}
	
		// Returns the value of the Node
		public int getValue() {
			return value;
		}
		
		// Sets the value of the Node
		public void setValue(int v) {
			value = v;
		}
		
		// Returns a pointer to the next item
		public Node getNext() {
			return next;
		}
		
		// Sets the value of the next item
		public void setNext(Node n) {
			next = n;
		}

		private int value;
		private Node next;
	}
	
	// Adds an element to the k-th point in the list
	public void add(int k, int v) throws IndexOutOfBoundsException {
		if (head == null) {
			head = new Node();
			head.setValue(v);
		} else {
			Node TMP = head;
			for (int i = 0; i < k-1; i++) {
				TMP = TMP.getNext();
			}
			
			Node N = new Node();
			N.setValue(v);
			N.setNext(TMP.getNext());
			TMP.setNext(N);
		}
	}
	
	// Delets an element to the k-th point in the list
	public void delete(int k) throws IndexOutOfBoundsException {
		Node TMP = head;
		for (int i = 0; i < k-1; i++) {
			TMP = TMP.getNext();
		}
		TMP.setNext((TMP.getNext()).getNext());
	}
	
	// Reads the k-th element of the list
	public int read(int k) throws IndexOutOfBoundsException {
		Node K = head;
		for (int i = 0; i < k; i++) {
			K = K.getNext();
		}
		return K.getValue();
	}
	
	// Returns the length of the list
	public int length() {
		Node N = head;
		int length = 0;
		
		while(N != null)
		{
			N = N.getNext();
			length++;
		}
		return length;
	}
	
	// Returns a list as a String
	public String toString() {
		Node N = this.head;
		String ts = "";
		if (N != null) ts = Integer.toString(N.getValue());
		while (N.getNext() != null) {
			N = N.getNext();
			ts += ", " + Integer.toString(N.getValue());
		}
		return "[" + ts + "]";
	}
	
	protected Node head = null;
}
