Singular Linked List

What is a singular linked list?

These linked lists are made up of a chain of nodes that are connected to each other in a linear fashion. The first node is called the head and has a pointer to the next node in the list. This node has a pointer to the next node as well as a data field to store an object. This chaining continues until the last node in the list, often called the tail, who's next pointer points to null.

Implementation of a singular linked list

public class LinkedList﹤E extends Comparable﹤? super E﹥﹥{

	private ListNode ﹤E﹥ head; 
	private int size;

	public UnorderedList(){
		head ﹦ new ListNode﹤E﹥();
		size ﹦ 0; 
	}

  public void add(E obj){
    if(isEmpty()){
      head.next ﹦ new ListNode﹤E﹥(obj, null);
      size﹢﹢;
      return;
    } 
    ListNode﹤E﹥ prev ﹦ head.next;
    head.next ﹦ new ListNode﹤E﹥(obj, prev);
    size﹢﹢;
  }

  public E remove(E obj){
    ListNode﹤E﹥ i ﹦ head.next; 
    ListNode﹤E﹥ prev ﹦ head;

    while(i﹗﹦null){
      if(i.info.equals(obj)){
        prev.next ﹦ i.next; 
        i.next ﹦ null;
        size﹣﹣;
        return i.info;
      }
      prev ﹦ i;
      i ﹦ i.next;
    }
    return null;
  }

  private static class ListNode﹤E﹥ {
    private E info; 
      private ListNode﹤E﹥ next;

      public ListNode(){
        next ﹦ null;
        info ﹦ null;
      }

      public ListNode(E obj, ListNode ﹤E﹥ nextNode){
        info ﹦ obj;
        next ﹦ nextNode;
      }
   }
}

This code can also have other functions to manipulate data.

Full course
Next Lesson