【发布时间】:2017-12-12 23:14:36
【问题描述】:
您好,我目前正在尝试解决这个问题(很遗憾,没有解决方案):
http://blog.gainlo.co/index.php/2016/06/12/flatten-a-linked-list/
基本上,您希望将具有 next 指针和 down 指针指向单链表的链表展平。
以下是我想出的,如果有任何错误或发现任何会破坏这一点的边缘情况,请纠正我。
static class Node {
Node next;
Node down;
int val;
Node(int val) {
this.val = val;
}
}
static Node flattenLinkedList(Node head) {
Queue<Node> q = new LinkedList<>();
q.add(head);
Node dummyhead = new Node(0);
Node pre = dummyhead;
while (!q.isEmpty()) {
Node current = q.poll();
while (current != null) {
pre.next = new Node(current.val);
pre = pre.next;
if (current.down != null) {
q.add(current.down);
}
current = current.next;
}
}
return dummyhead.next;
}
public static void main(String[] args) {
Node start = new Node(1);
start.next = new Node(2);
start.next.next = new Node(3);
start.next.next.next = new Node(4);
start.next.down = new Node(5);
start.next.down.down = new Node(8);
start.next.down.next = new Node(6);
start.next.next.next.down = new Node(7);
Node sol = flattenLinkedList(start);
}
P.S 我这样做是为了练习面试,而不是为了家庭作业。
【问题讨论】:
-
你自己写过单元测试吗?
-
@cricket_007,是的,认为它适用于网站上的示例,但想确定它是否普遍正确。
-
你认为它有效是什么意思?您是如何验证的?
-
你能展示你当前的单元测试吗?
-
“一个有下一个指针和下指针的链表”——这不是叫二叉树吗?
标签: java algorithm linked-list binary-tree