From 8202beb81eb5cc16f3021ffee304e1506340cf22 Mon Sep 17 00:00:00 2001 From: Nitin Gupta <66675656+manitgupt14@users.noreply.github.com> Date: Wed, 27 Oct 2021 18:53:07 +0530 Subject: [PATCH] LinkedList : Rotate a LinkedList LinkedList : Rotate a LinkedList --- RotateALinkedList.cpp | 100 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 RotateALinkedList.cpp diff --git a/RotateALinkedList.cpp b/RotateALinkedList.cpp new file mode 100644 index 0000000..1a8da07 --- /dev/null +++ b/RotateALinkedList.cpp @@ -0,0 +1,100 @@ +#include +using namespace std; + +struct Node { + int data; + struct Node *next; + Node(int x) { + data = x; + next = NULL; + } +}; + + + // } Driver Code Ends +/* + +struct Node { + int data; + struct Node *next; + Node(int x) { + data = x; + next = NULL; + } +}; + +*/ + +class Solution +{ + public: + //Function to rotate a linked list. + Node* rotate(Node* head, int k) + { + Node *a,*b; + a=head; + while(a->next!=NULL) + a=a->next; + + k--; + + b=head; + head=b->next; + a->next=b; + a=a->next; + while(k--) + { + b=head; + head=b->next; + a->next=b; + a=a->next; + } + + a->next=NULL; + return head; + } +}; + + + +// { Driver Code Starts. + +void printList(Node *n) +{ + while (n != NULL) + { + cout<< n->data << " "; + n = n->next; + } + cout<< endl; +} + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n, val, k; + cin>>n; + + cin>> val; + Node *head = new Node(val); + Node *tail = head; + + for(int i=0; i> val; + tail->next = new Node(val); + tail = tail->next; + } + + cin>> k; + + Solution ob; + head = ob.rotate(head,k); + printList(head); + } + return 1; +} + // } Driver Code Ends