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