Skip to content

Commit a8612b7

Browse files
author
Yan Cao
committed
Added Flatten Link List
1 parent c899d51 commit a8612b7

File tree

4 files changed

+77
-0
lines changed

4 files changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate 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 below figure.You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in way that all nodes at first level should come first, then nodes of second level, and so on.
3+
4+
Each node is a C struct with the following definition.
5+
6+
![pic](./img/flattenList.png)
7+
"""
8+
9+
class List():
10+
def __init__(self, data):
11+
self.data = data
12+
self.next = None
13+
self.child = None
14+
15+
def flatten_list(head):
16+
tail = head
17+
while tail.next:
18+
tail = tail.next
19+
20+
while head.next:
21+
if head.child:
22+
tail.next = head.child
23+
while tail.next:
24+
tail = tail.next
25+
head = head.next
26+
27+
# Note:
28+
# 题目22 23行之间用了一个tmp, 但我感觉没必要用...
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Given a linked list where every node represents a linked list and contains two pointers of its type:
3+
(i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)
4+
(ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code).
5+
All linked lists are sorted. See the following example
6+
```
7+
5 -> 10 -> 19 -> 28
8+
| | | |
9+
V V V V
10+
7 20 22 35
11+
| | |
12+
V V V
13+
8 50 40
14+
| |
15+
V V
16+
30 45
17+
```
18+
"""
19+
20+
class Node():
21+
def __init__(self, data):
22+
self.right = None
23+
self.down = None
24+
self.data = data
25+
26+
def flatten(node):
27+
if not node or not node.right:
28+
return node
29+
30+
return merge(node, flatten(node.right))
31+
32+
def merge(node1, node2):
33+
if not node1:
34+
return node2
35+
if not node2:
36+
return node1
37+
38+
if node1.data < node2.data:
39+
head = node1
40+
head.next = merge(node1.next, node2)
41+
else:
42+
head = node2
43+
head.next = merge(node1, node2.next)
44+
return head
45+
46+
# Notice:
47+
# This is very qiao miao. Using recursion is like DFS, so will first flatten from the end.
48+
# When we want to flatten the front part, the back parts are already flattened

coding_index.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
* [x] Combination Sum II
1414
* [x] Letter Combination of a Phone Number
1515
* [ ] 找零钱
16+
1617
-----
1718

1819
* [x] Subset

img/flattenList.png

14.9 KB
Loading

0 commit comments

Comments
 (0)