Friday, November 22, 2019

Print Linked List In ReverseOrder DS


package linkelist.example;

//Print Singly linked list in reverse order
public class LinkedListInReverseOrder {
 Node startNode = null;

 public static void main(String[] args) {
  LinkedListInReverseOrder dsLinkedList = new LinkedListInReverseOrder();

  Node n1 = new Node(10);
  Node n2 = new Node(20);
  Node n3 = new Node(30);
  Node n4 = new Node(40);
  Node n5 = new Node(50);
  Node n6 = new Node(60);
  Node n7 = new Node(70);
  Node n8 = new Node(80);

  dsLinkedList.startNode = n1;

  n1.setNext(n2);
  n2.setNext(n3);
  n3.setNext(n4);
  n4.setNext(n5);
  n5.setNext(n6);
  n6.setNext(n7);
  n7.setNext(n8);

  //with recursion
  //dsLinkedList.reverseOrderRecursion(dsLinkedList.startNode);
  
  //without recursion
  dsLinkedList.reverseOrder(dsLinkedList.startNode);
  

 }

   //Recursive approach.
 private void reverseOrderRecursion(Node startNode) {
  if (startNode == null) {
   return;
  }
  reverseOrderRecursion(startNode.getNext());
  System.out.print(startNode.getData() + " ");
 }
 
 public void reverseOrder(Node startNode) {
     Node pointer = startNode;
     Node previous = null, current = null;

     while (pointer != null) {
       current = pointer;
       pointer = pointer.getNext();

       // reverse the link
       current.setNext(previous);
       previous = current;
       startNode = current;
     }
     
     // Print elements
     while (startNode != null) {
   System.out.print(startNode.getData() + " ");
   startNode = startNode.getNext();
  }

   }
 
 // Print linked list.
 /*
  * private void printList(Node startNode) { while (startNode != null) {
  * System.out.print(startNode.getData() + " "); startNode = startNode.getNext();
  * } }
  */
}
package linkelist.example;

public class Node {

 private int data;
 private Node next;

 public Node(int data) {
  this.data = data;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }

 public Node getNext() {
  return next;
 }

 public void setNext(Node next) {
  this.next = next;
 }
}

Output:

80 70 60 50 40 30 20 10

No comments:

Post a Comment