Skip to content

Instantly share code, notes, and snippets.

@evanjmg
Created February 3, 2019 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanjmg/8247f77dbca951ba03f587667d95f75e to your computer and use it in GitHub Desktop.
Save evanjmg/8247f77dbca951ba03f587667d95f75e to your computer and use it in GitHub Desktop.
Rotation of Circular Linked List without Tail
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