File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Data-Structures/Linked-List Expand file tree Collapse file tree 1 file changed +45
-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+ // Reference to both head and k is given in the problem. So please ignore below two lines
18+ let head = ''
19+ let k = ''
20+ let i = 0
21+ let current = head
22+ while ( current ) {
23+ i ++
24+ current = current . next
25+ }
26+ k %= i
27+ current = head
28+ let prev = null
29+ while ( k -- ) {
30+ if ( ! current || ! current . next ) {
31+ return current
32+ } else {
33+ while ( current . next ) {
34+ prev = current
35+ current = current . next
36+ }
37+ prev . next = current . next
38+ current . next = head
39+ head = current
40+ }
41+ }
42+ return head
43+ }
44+
45+ main ( )
You can’t perform that action at this time.
0 commit comments