Skip to content

Instantly share code, notes, and snippets.

@rugyoga
Created February 16, 2023 20:34
Show Gist options
  • Select an option

  • Save rugyoga/c5d5b2deaacc669d4f433ae9929468d0 to your computer and use it in GitHub Desktop.

Select an option

Save rugyoga/c5d5b2deaacc669d4f433ae9929468d0 to your computer and use it in GitHub Desktop.
/* stackless version */
var flatten = function(head) {
const first = head;
var stack = null;
while (head != null) {
if (head.child != null) {
if (head.next != null) {
head.next.prev = stack;
stack = head.next;
}
head.next = head.child;
head.next.prev = head;
head.child = null;
}
if (head.next == null && stack != null) {
head.next = stack;
stack = stack.prev;
head.next.prev = head;
}
head = head.next;
}
return first;
};
/* stack version */
var flatten = function(head) {
const first = head;
var stack = [];
while (head != null) {
if (head.child != null) {
if (head.next != null) {
head.next.prev = null;
stack.push(head.next);
}
head.next = head.child;
head.next.prev = head;
head.child = null;
}
if (head.next == null && stack.length > 0) {
head.next = stack.pop();
head.next.prev = head;
}
head = head.next;
}
return first;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment