You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. 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.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation:
The input multilevel linked list is as follows:
1->2->NULL
|
3->NULL
Approach
Java
public class FlattenMultilevelDoublyLinkedList {static class ListNode {int val;public ListNode next;public ListNode prev;public ListNode child;ListNode() {}ListNode(int val) {this.val = val;}}public static void main(String[] args) {ListNode head = new ListNode(1);head.next = new ListNode(2);head.child = new ListNode(3);ListNode list = flatten(head);linkedListTraversal(list);}static ListNode flatten(ListNode head) {if (head == null)return head;flat(head, null);return head;}private static void linkedListTraversal(ListNode node) {while (node != null) {System.out.print(node.val + " ");node = node.next;}}static void flat(ListNode head, ListNode parent) {// if node child is present then// flatten itif (head.child != null) {flat(head.child, head.next);head.next = head.child;head.child = null;head.next.prev = head;}if (head.next == null) {if (parent != null) {head.next = parent;parent.prev = head;}} elseflat(head.next, parent);}}
C++
#include <bits/stdc++.h>using namespace std;//structure for linkedliststruct ListNode{int data;ListNode *prev;ListNode *next;ListNode *child;ListNode(int val){this->data=val;this->prev=NULL;this->next=NULL;this->child=NULL;}};void flat(ListNode *head,ListNode *parent){//if node child is present then//flatten itif(head->child!=NULL){flat(head->child,head->next);head->next=head->child;head->child=NULL;head->next->prev=head;}if(head->next==NULL){if(parent!=NULL){head->next=parent;parent->prev=head;}}elseflat(head->next,parent);}ListNode* flatten(ListNode* head){if(head==NULL)return head;flat(head,NULL);return head;}//function to traverse a linked//listvoid linkedListTraversal(ListNode *head){ListNode *temp=head;//iterate till we reach end of the linked//listwhile(temp!=NULL){//print the current//node datacout<<temp->data<<" ";//move to next nodetemp=temp->next;}}int main(){ListNode *head=new ListNode(1);head->next=new ListNode(2);head->child=new ListNode(3);ListNode *list=flatten(head);linkedListTraversal(list);return 0;}
No comments:
Post a Comment