Skip to content

Instantly share code, notes, and snippets.

@3dvkr
Last active August 8, 2022 20:45
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 3dvkr/6ec474f1b39173a31d541e66058acc08 to your computer and use it in GitHub Desktop.
Save 3dvkr/6ec474f1b39173a31d541e66058acc08 to your computer and use it in GitHub Desktop.
/*
Given a list, swap every two adjacent nodes. Something to think about: How would your code change if this were a linked list, versus an array?
Source: https://buttondown.email/cassidoo/archive/youve-got-to-get-up-every-morning-with-a-smile-on/
*/
// // with arrays
function swapPairs(arr) {
const swapped = [...arr]
for (let i = 0; i < swapped.length - 1; i = i + 2) {
const temp = swapped[i + 1]
swapped[i + 1] = swapped[i]
swapped[i] = temp
}
return swapped
}
console.log(swapPairs([1,2,3,4]))
// // with linked lists
class Node {
constructor(val, next = null) {
this.val = val
this.next = next
}
printList() {
const arr = []
let curr = this
while (curr !== null) {
arr.push(curr.val)
curr = curr.next
}
return arr.join(" -> ") + " -> null"
}
}
function createLL(n) {
let list = new Node(n)
for (let i = n - 1; i >= 0; i--) {
const llnode = new Node(i, list)
list = llnode
}
return list
}
function swapll(ll) {
let curr = ll
while(curr !== null) {
const val = curr.val
const next = curr.next
const nextVal = next.val
curr.val = nextVal
curr.next.val = val
if (curr.next.next && curr.next.next.next) {
curr = curr.next.next
} else {
curr = null
}
}
return ll
}
const list = createLL(5)
console.log(list.printList())
console.log(swapll(list).printList())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment