상세 컨텐츠

본문 제목

[Go] Linked List - Flatten a Multilevel Doubly Linked List

카테고리 없음

by Gopythor 2022. 5. 21. 18:32

본문

728x90
반응형

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.

 

Example 1:

Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:

Example 2:

Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:

Example 3:

Input: head = []
Output: []
Explanation: There could be empty list in the input.

 

Constraints:

  • The number of Nodes will not exceed 1000.
  • 1 <= Node.val <= 105

 

How the multilevel linked list is represented in test cases:

We use the multilevel linked list from Example 1 above:

 1---2---3---4---5---6--NULL
         |
         7---8---9---10--NULL
             |
             11--12--NULL

The serialization of each level is as follows:

[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]

To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:

[1,    2,    3, 4, 5, 6, null]
             |
[null, null, 7,    8, 9, 10, null]
                   |
[            null, 11, 12, null]

Merging the serialization of each level and removing trailing nulls we obtain:

[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]

 

My code

func flatten(root *Node) *Node {
	if root != nil {
		helper(root)
	}
	return root

}

func helper(root *Node) *Node {
	end := &Node{}

	for root != nil {
		if root.Child != nil {
			end = helper(root.Child)
			if root.Next != nil {
				end.Next = root.Next
				root.Next.Prev = end

			}
			root.Next = root.Child
			root.Child.Prev = root
			root.Child = nil

		}
		if root.Next == nil {
			break
		}
		root = root.Next

	}

	return root

}
  • First I didn't know how to return tail and head.
  • After refer other's code, Just i needed to make other function.
  • flatten will call helper when node is not nil.
  • Empty end node is declared.
  • For loop will run until node is not nil.
  • when node has child, recursive call will be called.
  • End will have end of node
  • root which has child will be checked whethere Next is nil or not.
  • If Next is not nil, end.Next will have root.Next so that it can be flattered.

sample 0 ms submission

func flatten(root *Node) *Node {
    stack:=[]*Node{}
    cur:=root
    for cur!=nil{
        if cur.Child!=nil{
            if cur.Next!=nil{
                stack=append(stack,cur.Next)
            }
            child:=cur.Child
            cur.Child=nil
            cur.Next=child
            child.Prev=cur
        }else if cur.Next==nil&&len(stack)>0{
            cur.Next=stack[len(stack)-1]
            stack=stack[:len(stack)-1]
            cur.Next.Prev=cur
        }
        
        cur=cur.Next
    }
    
    return root
}
  • stack slice will be made for keep node.
  • for loop will run until node is nil 
  • if Child is not nil, if condition will check cur.Next is nil or not.
  • if not, cur.Next will be in stack slice.
  • later is same process
  • Child will be cur.Next and Child.Prev will be cur and Child will be nil.
  • When cur.Next and nil and stack has value, cur.Next will have LIFO
  • and stack will be deleted from end of slice.

sample 2 ms submission

func flatten(head *Node) *Node {
    if head == nil {
        return head
    }
    flattenChild(head)
    return head
}

func flattenChild(node *Node) *Node {
    curr := node
    var lastNode *Node
    for curr!=nil {
        if curr.Next == nil {
            lastNode = curr
        }  
        if curr.Child == nil {
            curr = curr.Next
            continue
        }
        tmpNext:= curr.Next
        lNode := flattenChild(curr.Child)
        curr.Next = curr.Child
        curr.Child.Prev = curr
        curr.Child = nil

        lNode.Next = tmpNext
        if tmpNext != nil {
            tmpNext.Prev = lNode
        }
        lastNode = lNode
        curr = tmpNext
    }
    return lastNode
}
  • This code has two function.
  • one is returning head, another is returning tail(end of node).
  • last Node was declared for keep last Node address.
  • For loop will run until curr is nil.
  • First if will check curr.Next is nil or not.
  • If so, lastNode will have curr.
  • After That if condition checks child is nil or not.
  • if child is nil, curr.Next will be curr.
  • and continue will make you return to beginning
  • if curr.Child is not nil, for loop is going down.
  • When next is nil and curr.Child is nil then this code will return end of node.
  • when next is not nil and curr.Child is nil, it will procedd until next is nil.
  • tmpNext will have next node of node which has child.
  • lNode will also have end of node.
  •        lastNode = Node and curr = tmpNext this code doesn't need.

 

sample 3 ms submission & sample 2800 KB submission

func flatten(root *Node) *Node {
    if root == nil {
        return nil
    }
    
    stack := []*Node{}
    stack = append(stack, root)
    temp := &Node{}
    for len(stack) > 0 {
        top := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        if top == nil {
            continue
        }
        temp.Next = top
        top.Prev = temp
        temp = top
        for temp.Child == nil && temp.Next != nil {
            temp = temp.Next
        }
        stack = append(stack, temp.Next)
        stack = append(stack, temp.Child)
        temp.Child = nil
    }
    root.Prev = nil
    return root
}

sample 4 ms submission

func flatten(root *Node) *Node {
    // 思路一:这个肯定是直接用自己深度遍历
    for head := root; head != nil; head = head.Next {
        if head.Child != nil {
            tmp, ch := head.Next, flatten(head.Child)
            head.Child, head.Next, ch.Prev = nil, ch, head
            for ch.Next != nil { // (1) 这会形成O(n²)但写起来简单
                ch = ch.Next
            }
            ch.Next = tmp
            if tmp != nil {
                tmp.Prev = ch
            }
        }
    }
    return root
}

sample 5 ms submission

func flatten(root *Node) *Node {
	flattenTraverse(root, nil)
	return root
}

func flattenTraverse(head *Node, rest *Node) *Node {
	if head == nil {
		return head
	}
	if head.Child != nil {
		flattenTraverse(head.Child, head.Next)
		head.Next = head.Child
		head.Next.Prev = head
		head.Child = nil
	}
	if head.Next == nil {
		if rest != nil {
			head.Next = rest
			rest.Prev = head
		}
		return head
	}
	return flattenTraverse(head.Next, rest)
}

sample 2700 KB submission

func getNextNode (head *Node) *Node {
    tmp:= head
    var ret *Node
    
    for (tmp != nil) {       
        ret = tmp
        tmp = tmp.Next
    }
    return ret
}

func flatten(root *Node) *Node {
    
    if (root == nil ) {return nil}
    tmp:= root
    
    for (tmp != nil) {
        
        if tmp.Child != nil {
            next:= getNextNode (tmp.Child)
            // stich
            if (tmp.Next != nil) {
                tmp.Next.Prev = next
            }
            next.Next = tmp.Next
            tmp.Next = tmp.Child
            tmp.Child.Prev = tmp
            tmp.Child = nil
        }
        
        tmp = tmp.Next
    }
    
    return root
}

sample 2900 KB submission

func flatten(root *Node) *Node {
    if root == nil {
        return root
    }
    a,_:=f(root)
    return a
}

func f(cur *Node) (*Node, *Node){
    last := cur
    if cur.Next != nil {
        nextFirst, nextLast := f(cur.Next)
        cur.Next = nextFirst
        nextFirst.Prev = cur
        last = nextLast
    }
    
    if cur.Child != nil {
        childFirst, childLast := f(cur.Child)
        childLast.Next = cur.Next
        
        if cur.Next != nil {
            cur.Next.Prev = childLast
        } else {
            last = childLast
        }
        
        cur.Next = childFirst
        childFirst.Prev = cur
    }
    cur.Child = nil
    
    return cur, last
}

sample 3000 KB submission

func flatten(root *Node) *Node {
    if root == nil { return root }
    pseudoHead := &Node{Next:root}
    flatten_dfs(pseudoHead, root)
    pseudoHead.Next.Prev = nil
    return pseudoHead.Next
}

func flatten_dfs(prev, curr *Node) *Node {
    if curr == nil { return prev}
    curr.Prev = prev
    prev.Next = curr
    
    tempNext := curr.Next
    tail := flatten_dfs(curr, curr.Child)
    curr.Child = nil
    return flatten_dfs(tail, tempNext)
}
728x90
반응형

댓글 영역