Smoothing a tiered list

Question

  • Given a linked list, where in addition to the next pointer, each node has a child pointer that may or may not point to a separate list.

  • Given that the head of the first list smoothes the list so that all nodes are displayed in a sibling linked list.

Purpose .

We need to smooth the list so that all nodes of the first level should be the first, then nodes of the second level, etc.

enter image description here

The above list should be converted to

10-> 5-> 12-> 7-> 11-> 4-> 20-> 13-> 17-> 6-> 2-> 16-> 9-> 8-> 3-> 19-> 15

My approach:

1) Create an empty queue
2) while(Queue is not empty AND head.next!=null AND head.child!=null)
     2a) while(head!=null)
           if(head.child!=null)
               Enqueue(head.child)
           newList = head;
           head = head.next;
           newList = newList.next;
     2b)head = deQ();

Is this approach right?

+4
2

( ), . ( , , .) , , finger2 finger1. finger1 , , node , "" finger2 , , finger1 finger1 .

finger1 = finger2 = head;
while finger2 is not Null:
  while finger1.next is not Null: finger1 = finger1.next
  while finger2 is not Null and finger2.child is Null: finger2 = finger2.next
  if finger2 is not Null:
    finger1.next = finger2.child
    finger2.child = Null   
+3

, , .

node *flatten(node *head) {
    stack<node *> s;
    node *curr = root;
    while (1) {
        if (curr->next) { // keep moving in current streak
            if (curr->child)
                s.push(curr);
            curr = curr->next;
        }
        else { // attach child branch and continue from there
            if (s.empty())
                return head;
            curr->next = s.top()->next;
            s.top()->next = NULL;
            s.pop();
            curr = curr->next;
        }
    }
}
0

Source: https://habr.com/ru/post/1546616/


All Articles