
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rotate a Linked List by K Places in C++
Suppose we have a linked list. We have to rotate the list to the right by k places. The value of k will be positive. So if the list is like [1 −> 2 −> 3 −> 4 −> 5 −> NULL], and k = 2, then the output will be [4 −> 5 −> 1 −> 2 −> 3 −> NULL]
Let us see the steps −
If the list is empty, then return null
len := 1
create one node called tail := head
-
while next of tail is not null
increase len by 1
tail := next of tail
next of tail := head
k := k mod len
newHead := null
-
for i := 0 to len − k
tail := next of tail
newHead := next of tail
next of tail := null
return newHead
Let us see the following implementation to get better understanding −
Example
#includeusing namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int data){ val = data; next = NULL; } }; ListNode *make_list(vector v){ ListNode *head = new ListNode(v[0]); for(int i = 1; i next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } void print_list(ListNode *head){ ListNode *ptr = head; cout next){ cout val next; } cout next){ len++; tail = tail->next; } tail->next = head; k %= len; ListNode* newHead = NULL; for(int i = 0; i next; } newHead = tail->next; tail->next = NULL; return newHead; } }; main(){ Solution ob; vector v = {1,2,3,4,5,6,7,8,9}; ListNode *head = make_list(v); print_list(ob.rotateRight(head, 4)); }
Input
[1,2,3,4,5,6,7,8,9], 4
Output
[6, 7, 8, 9, 1, 2, 3, 4, ]
Advertisements