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

Cracking the Coding Interview

Ace your Technical Interview Try Algorithms

Cracking the Coding Interview will tell you exactly what you need to know to land your dream job at Google, Amazon, Microsoft or any other big tech companies. Packed with over 189 interview questions and detailed solutions, this book will help you train for the classic white-board technical interview. A must have for any CS major.

$ Check price
39.9539.95Amazon 4.5 logo(266+ reviews)

More Algorithms resources

Want to avoid becoming a code monkey?

Code Complete 2

Want to avoid becoming a code monkey? Try Good Practice

This book synthesizes the most effective techniques and must-know principles into clear, pragmatic guidance. No matter what your experience level, development environment, or project size, this book will inform and stimulate your thinking - and help you build the highest quality code.

$ Check price
54.9954.99Amazon 4.5 logo(291+ reviews)

More Good Practice resources

Ad