Java implementation of data structure single linked representation of example of Java single linked list

  • 2020-04-01 03:09:00
  • OfStack



public class NodeList<E> {
 private static class Node<E> { //Node class
  E data; //Data on a node
  Node<E> next; //Point to the next node
  Node(E e) {
   this.data = e;
   this.next = null;
  }
 }
 private Node<E> head; //The header node of the linked list
 private Node<E> last; //The tail node of a linked list
 private Node<E> other = null;
 private int length = 0; //Number of nodes
 
 public NodeList() {
  //The default node is empty
  this.head = new Node<E>(null);
 }
 
 public NodeList(E data) {
  this.head = new Node<E>(data);
  this.last = head;
  length++;
 }
 
 public void add(E data) {
  if (isEmpty()) {
   head = new Node<E>(data);
   last = head;
   length++;
  } else {
   Node<E> newNode = new Node<E>(data);
   last.next = newNode;
   last = newNode;
  }
 }

 
 public E get(int index){
  if(index<0 || index>length){
   throw new IndexOutOfBoundsException(" The index of crossing the line :"+index);
  }
  other = head;
  for(int i=0;i<index;i++){
   other = other.next;
  }
  return other.data;
 }

 
 public boolean set(E oldValue,E newValue){
  other = head;
  while(other!=null){
   if(other.data.equals(oldValue)){
    other.data = newValue;
    return true;
   }
   other = other.next;
  }
  return false;
 }

 
 public boolean add(E data, E insertData) {
  other = head;
  while (other != null) {
   if (other.data.equals(data)) {
    Node<E> newNode = new Node<E>(insertData);
    Node<E> temp = other.next;
    newNode.next = temp;
    other.next = newNode;
    length++;
    return true;
   }
   other = other.next;
  }
  return false;
 }
 
 public boolean contains(E data){
  other = head;
  while(other!=null){
   if(other.data.equals(data)){
    return true;
   }
   other = other.next;
  }
  return false;
 }

 
 public boolean remove(E data){
  other = head;
  Node<E> temp = head;  //Temporary variable to hold the previous node
  while(other!=null){
   if(other.data.equals(data)){
    temp.next = other.next;
    length--;
    return true;
   }
   temp = other;
   other = other.next;
  }
  return false;
 }

 
 public boolean isEmpty() {
  return length == 0;
 }
 
 public void clear() {
  this.head = null;
  this.length = 0;
 }
 
 public void printLink() {
  if(isEmpty()){
   System.out.println(" An empty list ");
  }else{
   other = head;
   while (other != null) {
    System.out.print(other.data);
    other = other.next;
   }
   System.out.println();
  }
 }
}


Related articles: