package com.clearurdoubt.impl;
 
/**
 * 
 * @author Sai Gowtham Badvity
 * SinglyLinkedList Implementation 
 * @param <T> type of the object LinkedList holds.
 *
 */
public class MySinglyLinkedList<T> 
{
	private class Node
	{
		T value;
		Node next;
	}
	
	private Node head = null, tail = null;
	
	
	/** 
	 * Add Node to the List
	 * @param val
	 */
	public void add(T val)
	{
		addLast(val);
	}
	
	
	/**
	 * Add Node in the beginning the List
	 * @param val
	 */
	public void addFirst(T val)
	{
		Node newNode = new Node();
		
		newNode.value = val;
		newNode.next = head;
			
		head = newNode;
		
		if(tail == null)
			tail = newNode;
	}
	
	
	/**
	 * Add Node at the end of the List
	 * @param val
	 */
	public void addLast(T val)
	{
		if(head == null)
		{
			addFirst(val);
			return;
		}
		
		Node newNode = new Node();
		
		newNode.value = val;
		newNode.next = null;
		
		tail.next = newNode;
		tail = newNode;
	}
	
	/**
	 * Remove first node 
	 */
	public void removeFirst()
	{
		if(head == null)
			return;
		else
		{
			head = head.next;
		}
	}
	
	/**
	 * Remove last node
	 */
	public void removeLast()
	{
		Node temp = head;
		
		while(temp.next != tail)
		{
			temp = temp.next;
		}
		
		temp.next = null;
		
		tail = temp;
	}
	
	/**
	 * Print the elements
	 */
	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder();
		
		Node temp = head;
		
		do
		{
			builder.append( temp.value + " -> ");
			temp = temp.next;
		} while(temp.next != null);
		
		builder.append( temp.value );
		
		return builder.toString();
	}
	
}