File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Data-Structures/Linked-List Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * A LinkedList based solution for Rotating a List to the right by k places
3+ */
4+
5+ function main ( ) {
6+ /*
7+ Problem Statement:
8+ Given a linked list, rotate the list to the right by k places, where k is non-negative.
9+
10+ Note:
11+ * While Solving the problem in given link below, don't use main() function.
12+ * Just use only the code inside main() function.
13+ * The purpose of using main() function here is to aviod global variables.
14+
15+ Link for the Problem: https://leetcode.com/problems/rotate-list/
16+ */
17+ const head = '' , k = '' // Reference to both head and k is given in the problem. So please ignore this line
18+ let i = 0 ;
19+ let current = head
20+ while ( current ) {
21+ i ++
22+ current = current . next
23+ }
24+ k %= i
25+ current = head
26+ let prev = null
27+ while ( k -- ) {
28+ if ( ! current || ! current . next ) {
29+ return current
30+ } else {
31+ while ( current . next ) {
32+ prev = current
33+ current = current . next
34+ }
35+ prev . next = current . next
36+ current . next = head
37+ head = current
38+ }
39+ }
40+ return head
41+ }
42+
43+ main ( )
You can’t perform that action at this time.
0 commit comments