Count rotations in sorted and rotated linked list | Program for count number of rotations in sorted linked list . ; Linked list node ; Function that count number of rotation in singly linked list . ; declare count variable and assign it 1. ; declare a min variable and assign to data of head node . ; check that while head not equal to NULL . ; if min value is greater then head -> data then it breaks the while loop and return the value of count . ; head assign the next value of head . ; Function to push element in linked list . ; Allocate dynamic memory for newNode . ; Assign the data into newNode . ; newNode -> next assign the address of head node . ; newNode become the headNode . ; Display linked list . ; Driver functions ; Create a node and initialize with NULL ; push ( ) insert node in linked list . 15 -> 18 -> 5 -> 8 -> 11 -> 12 ; Function call countRotation ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; int countRotation ( struct Node * head ) { int count = 0 ; int min = head -> data ; while ( head != NULL ) { if ( min > head -> data ) break ; count ++ ; head = head -> next ; } return count ; } void push ( struct Node * * head , int data ) { struct Node * newNode = new Node ; newNode -> data = data ; newNode -> next = ( * head ) ; ( * head ) = newNode ; } void printList ( struct Node * node ) { while ( node != NULL ) { printf ( " % d ▁ " , node -> data ) ; node = node -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 11 ) ; push ( & head , 8 ) ; push ( & head , 5 ) ; push ( & head , 18 ) ; push ( & head , 15 ) ; printList ( head ) ; cout << endl ; cout << " Linked ▁ list ▁ rotated ▁ elements : ▁ " ; cout << countRotation ( head ) << endl ; return 0 ; }