Mahmoud_Hawara

Rotate Left in Linked List

Dec 19th, 2022 (edited)
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. // Assignment #1
  2.  
  3. public class Solver
  4. {
  5.     public static void main(String args[])
  6.     {
  7.         LinkedList list = new LinkedList();
  8.  
  9.         list.insertFirst(new Node(1));
  10.         list.insertFirst(new Node(2));
  11.         list.insertFirst(new Node(3));
  12.         list.insertFirst(new Node(4));
  13.        
  14.         System.out.print("\nThe List before Rotating Left: ");
  15.         list.print();
  16.  
  17.         rotateLeft(list);
  18.  
  19.         System.out.print("The List after Rotating Left: ");
  20.         list.print();
  21.  
  22.         System.out.println();
  23.     }
  24.  
  25.     public static void rotateLeft(LinkedList list)
  26.     {
  27.         if (list.isEmpty())
  28.         {
  29.             System.out.println("The List is Empty");
  30.             return;
  31.         }
  32.         if (list.First.next != null)
  33.         {
  34.             Node curr = list.First;
  35.             while (curr.next != null)
  36.             {
  37.                 curr = curr.next;
  38.             }
  39.             curr.next = list.First;
  40.             list.First = list.First.next;
  41.             curr.next.next = null;
  42.         }
  43.         System.out.println("-----\nDone, The List is rotated left\n-----");
  44.     }
  45. }
  46.  
  47. class Node
  48. {
  49.     int data;
  50.     Node next;
  51.  
  52.     public Node(int d)
  53.     {
  54.         data = d;
  55.     }
  56. }
  57.  
  58. class LinkedList
  59. {
  60.     Node First;
  61.  
  62.     void insertFirst(Node newNode)
  63.     {
  64.         newNode.next = First;
  65.         First = newNode;
  66.         // System.out.println("Done, Node is inserted at First");
  67.     }
  68.  
  69.     Node deleteFirst()
  70.     {
  71.         if (isEmpty())
  72.         {
  73.             System.out.println("The List is Empty");
  74.             return null;
  75.         }
  76.  
  77.         Node temp = First;
  78.         First = First.next;
  79.         temp.next = null;
  80.  
  81.         // System.out.println("Done, First Node is deleted");
  82.         return temp;
  83.     }
  84.  
  85.     void print()
  86.     {
  87.         if (isEmpty())
  88.         {
  89.             System.out.println("The List is Empty");
  90.             return;
  91.         }
  92.         Node curr = First;
  93.         while (curr != null)
  94.         {
  95.             System.out.printf("%d ", curr.data);
  96.             curr = curr.next;
  97.         }
  98.         System.out.println();
  99.     }
  100.  
  101.     boolean isEmpty()
  102.     {
  103.         return First == null;
  104.     }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment