I am trying to solve Flatten a Multilevel Doubly Linked List
problem on a leetcode. I am able to create a singly linked list from an array but don't know how to create a doubly linked list.
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.
Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.
Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.
Ques link: Flatten a Multilevel Doubly Linked List
My code:
/**
* // Definition for a Node.
* function Node(val,prev,next,child) {
* this.val = val;
* this.prev = prev;
* this.next = next;
* this.child = child;
* };
*/
/**
* @param {Node} head
* @return {Node}
*/
var flatten = function(head) {
let array=[];
let list=head;
const childAdd=(node)=>{
while(node){
array.push(node.val);
if(node.child)
childAdd(node.child);
node=node.next;
}
}
while(list){
array.push(list.val);
if(list.child)
childAdd(list.child);
list=list.next;
}
console.log(array)
let resultList=null
for(let i=array.length-1; i>=0; i--){
resultList={
val:array[i],
next:resultList,
}
let prev=null;
while(head){
delete head.child
resultList.prev=prev;
prev=head;
head=head.next;
}
console.log(resultList)
return resultList;
};
Output:
[
1, 2, 3, 7, 8,
11, 12, 9, 10, 4,
5, 6
]
{
val: 1,
next: { val: 2, next: { val: 3, next: [Object] } },
prev: <ref *1> {
val: 5,
prev: { val: 4, prev: [Object], next: [Circular *1] },
next: { val: 6, prev: [Circular *1], next: null }
}
}
Expected Output:
The linked list [1,2,3,7,8,11,12,9,10,4,5,6] is not a valid doubly linked list.
Expected: [1,2,3,7,8,11,12,9,10,4,5,6]
How can I add prev
which points to the previous node of the list in my list resultList
?
PS: I don't want a solution to this problem instead I want to know how can I create a doubly linked list from an array.
CodePudding user response:
The hardest part is creating the list from the arr. Basically we iterate the array creating nodes, connect node to previous and connect previous to node. The trick here is when encountering null
is to set a pointer (bol
) to beginning of current list then while still encountering null we increment the bol
. Finally when we do find a value we know to create a node that is a child of bol
.
For completeness I added the solution (which is the easy part) but feel free to find it yourself.
function Node(val, prev, next, child) {
this.val = val;
this.prev = prev;
this.next = next;
this.child = child;
};
function create_list(arr) {
var prev = null;
var first = null;
var bol = null;
var result = null;
while (arr.length) {
var val = arr.shift();
if (val === null) {
if (bol) {
bol = bol.next;
} else {
bol = first;
prev = null;
}
} else {
var node = new Node(val, prev, null, null);
if (!result) {
result = node;
}
if (bol) {
bol.child = node;
bol = null;
}
if (node.prev) {
node.prev.next = node;
} else {
first = node;
}
prev = node;
}
}
return result;
}
var head = [1, 2, 3, 4, 5, 6, null, null, null, 7, 8, 9, 10, null, null, 11, 12];
var copy = [...head];
var list = create_list(head);
function flatten(list) {
var arr = [];
while (list) {
arr.push(list.val);
if (list.child) {
var brr = flatten(list.child);
arr = arr.concat(brr);
}
list = list.next;
}
return arr;
}
console.log("list as array: " JSON.stringify(copy))
console.log("flattened list: " JSON.stringify(flatten(list)))
console.log("example 2: " JSON.stringify(flatten(create_list([1,2,null,3]))))
console.log("example 3: " JSON.stringify(flatten(create_list([]))))
.as-console-wrapper {
max-height: 100% !important;
}
CodePudding user response:
function arrayToDoublyLinkedList(array) {
let curr;
let next = null;
let prev = null;
// go backwards so we end up with curr being the head
for(let i = array.length - 1; i >= 0; --i) {
curr = {
val: array[i],
prev: null, // except for the head, will set to a node on the next iteration
next: next,
child: null, // required to be null by the leetcode problem statement
};
if (null !== next) {
next.prev = curr;
}
next = curr;
}
return curr;
}
console.log(arrayToDoublyLinkedList([1,2,3,4,5,6,7,8]));
CodePudding user response:
LeetCode expects you to return a Node instance, i.e. an object with four properties (also including child
).
And the prev
property can be set correctly when you set the next
: that next node's prev
property should become a back reference to the object of which you set the next
property.
So replace this block of code (which misses a closing brace):
for(let i=array.length-1; i>=0; i--){
resultList={
val:array[i],
next:resultList,
}
let prev=null;
while(head){
delete head.child
resultList.prev=prev;
prev=head;
head=head.next;
}
With this:
for (let i = array.length - 1; i >= 0; i--) {
resultList = new Node(array[i], null, resultList, null);
if (resultList.next) resultList.next.prev = resultList;
}
Other remark
This solution will pass the tests, but it is not very efficient. It uses O(n) extra space, while this can be done with O(1) extra space:
- Avoid creating arrays
- Avoid creating new
Node
instances -- reuse the ones you already have