02. Implementing a Node

We'll be using Java Generics in our guide here, so it's highly recommended to learn that before moving on.

Implementing a Node is simple. It should store a generic element along with get and set methods to retrieve and mutate that element.

Additionally, since we are using this for a singly-linked list, it should have a next pointer, which points to the next node in the sequence.

/** 
 *  A Node object implementation to hold data in a LinkedList.
 *  
 *  @author  CodeSnipcademy
 *  @version  1.0.0 Jan 07, 2015
 */
public class Node<E> {
  private Node<E> next;   // Points to the next Node
  private E data;         // Holds data to be     | stored in Node
 
  /**
   * Create a new node with no next Node and no     | data.
   */
  public Node() {
    this(null, null);
  }
 
  /** 
   * Create a new Node with given data.
   *
   * @param  inputData - element to be stored
   */
  public Node(E inputData) {
    this(inputData, null);  
  }
 
  /** 
   * Create a new Node with data at the given index.
   * 
   * @param  inputData - element to be stored
   * @param  inputNext - next Node to be pointed to 
   */ 
  public Node(E inputData, Node<E> inputNext) {
    this.next = inputNext;
    this.data = inputData;
  }
 
  /**
   * Retrieve data of current Node.
   * @return  data - data stored in this Node
   */     
  public E getData() {
    return this.data;
  }
 
  /**
   * Set new data to Node.
   * @param  inputData - data stored in this Node
   */     
  public void setData(E inputData) {
    this.data = inputData;
  }
 
  /**
   * Return the next Node in the sequence.
   * @return  next - next data in the Node
   */     
  public Node<E> getNext() {
    return this.next;
  }
 
  /**
   * Set next value in current Node.
   * @param  inputNode - next Node to be set
   */     
  public void setNext(Node<E> inputNode) {
    this.next = inputNode;
  }
}

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ace your Technical Interview

Algorithms

Ace your Technical Interview Try Algorithms

This fourth edition of Algorithms is the leading textbook on algorithms today and is widely used in universities worldwide. This book surveys the most important computer algorithms currently in use and provides a full treatment of data structures and algorithms for sorting, searching, graph processing, and string processing.

$ Check price
89.9989.99Amazon 4.5 logo(148+ reviews)

More Algorithms resources

Ad