Created
February 3, 2019 19:46
-
-
Save evanjmg/8247f77dbca951ba03f587667d95f75e to your computer and use it in GitHub Desktop.
Rotation of Circular Linked List without Tail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createNode = (value) => ({ | |
value, | |
next: null, | |
}) | |
class CircularLinkedList { | |
constructor() { | |
this.length = 0 | |
this.head = null | |
} | |
push(value) { | |
const node = createNode(value) | |
if (!this.head) { | |
this.head = node | |
} else { | |
let length = this.length | |
let current = this.head | |
while (length > 1) { | |
current = current.next | |
length-- | |
} | |
current.next = node | |
} | |
node.next = this.head | |
this.length++ | |
return node | |
} | |
append(value) { | |
const node = createNode(value) | |
node.next = this.head | |
this.head = node | |
this.length++ | |
} | |
print() { | |
const values = [] | |
let current = this.head | |
let length = this.length | |
while (length > 0) { | |
values.push(current.value) | |
current = current.next | |
length-- | |
} | |
return values.join(' => ') | |
} | |
// counter clockwise | |
rotate(n) { | |
let i = 0 | |
while (i < n) { | |
let length = 1 | |
while (length < this.length) { | |
this.head = this.head.next | |
length++ | |
} | |
i++ | |
} | |
} | |
} | |
const list = new CircularLinkedList() | |
list.push('a') | |
list.push('b') | |
list.push('c') | |
list.push('d') | |
console.log(list.print()) | |
list.rotate(3) | |
console.log(list.print()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment