Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions RotateALinkedList.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#include <bits/stdc++.h>
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<n-1; i++)
{
cin>> 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