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;
  }
}

Ace your Technical Interview

Introduction to Algorithms

Ace your Technical Interview Try Algorithms

Introduction to Algorithms uniquely combines rigor and comprehensiveness. The book covers a broad range of algorithms in depth, yet makes their design and analysis accessible to all levels of readers. The algorithms are described in English and in a pseudocode designed to be readable by anyone who has done a little programming.

$ Check price
9999Amazon 4.5 logo(418+ reviews)

More Algorithms resources

Learn how data is stored

Data Structures and Algorithms in Java

Learn how data is stored Try Data Structures

Algorithms are the procedures that software programs use to manipulate data structures. Besides clear and simple example programs, the author includes a workshop as a small demonstration program executable on a Web browser. The programs demonstrate in graphical form what data structures look like and how they operate.

$ Check price
64.9964.99Amazon 4.5 logo(97+ reviews)

More Data Structures resources

Ad