Reverse a Singly Linked List

Singly Linked Lists are a type of data structure. It is a type of list. In a singly linked list each node in the list stores the contents of the node and a pointer or reference to the next node in the list. It does not store any pointer or reference to the previous node.

package com.tuturself.programs;

public class SingleLinkedList < T > {

 private Node < T > startNode;

 /**
  * @return the startNode
  */
 public Node < T > getStartNode() {
  return startNode;
 }

 /**
  * @param startNode the startNode to set
  */
 public void setStartNode(Node < T > startNode) {
  this.startNode = startNode;
 }


 public boolean addElement(T element) {
  Node < T > node = new Node < T > ();
  node.setValue(element);
  Node < T > temp = startNode;
  while (true) {
   if (temp == null) {
    startNode = node;
    break;
   } else if (temp.nextNode == null) {
    temp.setNextNode(node);
    break;
   } else {
    temp = temp.getNextNode();
   }
  }
  return true;
 }


 public void iterate() {

  Node < T > node = startNode;
  while (true) {
   if (node == null) {
    break;
   }
   System.out.print(node.getValue() + "\n");
   node = node.getNextNode();
  }
 }


 public void reverse() {
  Node < T > prev = null;
  Node < T > current = startNode;
  Node < T > next = null;
  while (current != null) {
   next = current.getNextNode();
   current.setNextNode(prev);
   prev = current;
   current = next;
  }
  startNode = prev;
 }


private class Node < T > {
  private T value;
  private Node < T > nextNode;
  /**
   * @return the value
   */
  public T getValue() {
   return value;
  }
  /**
   * @param value the value to set
   */
  public void setValue(T value) {
   this.value = value;
  }
  /**
   * @return the nextNode
   */
  public Node < T > getNextNode() {
   return nextNode;
  }
  /**
   * @param nextNode the nextNode to set
   */
  public void setNextNode(Node < T > nextNode) {
   this.nextNode = nextNode;
  }

 }


 public static void main(String a[]) {
  SingleLinkedList < Integer > singleLinkedList = new SingleLinkedList < Integer > ();
  singleLinkedList.addElement(3);
  singleLinkedList.addElement(32);
  singleLinkedList.addElement(54);
  singleLinkedList.addElement(89);
  System.out.println("Iterating Over link list");
  singleLinkedList.iterate();
  System.out.println("Reversing link list");
  singleLinkedList.reverse();
  singleLinkedList.iterate();
 }

}

Output:

Iterating Over link list
3
32
54
89
Reversing link list
89
54
32
3

 

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself