题目链接:https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/
把链表旋转过来看做一棵树,前序遍历
参考了通过的代码
//迭代深搜
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { func flatten(_ head: Node?) -> Node? { if head == nil { return nil } var nodeStack = [Node?]() let root: Node? = Node.init(-1) root?.next = head nodeStack.append(head) var prev = root, cur:Node? = nil while !nodeStack.isEmpty { cur = nodeStack.removeLast() prev?.next = cur cur?.prev = prev if cur?.next != nil { nodeStack.append(cur?.next) } if cur?.child != nil { nodeStack.append(cur?.child) cur?.child = nil } prev = cur } root?.next?.prev = nil return head } }
|
//递归调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { func flatten(_ head: Node?) -> Node? { var ptr = head ,nextPtr = head, Child = head while ptr != nil { if ptr?.child != nil { nextPtr = ptr?.next Child = ptr?.child Child?.prev = ptr ptr?.next = Child Child = flatten(Child) while Child?.next != nil { Child = Child?.next } Child?.next = nextPtr if nextPtr != nil { nextPtr?.prev = Child } ptr?.child = nil ptr = nextPtr }else{ ptr = ptr?.next } } return head } }
|