【发布时间】:2019-05-19 11:52:33
【问题描述】:
我有一个关于我正在参加的编码课程的期末复习的问题。它要求将 3 个链表合并为 1 个链表。我遇到的问题是在合并列表时,我可以按升序合并三个列表,但我错过了第二个列表 23 和 25 的最后 2 个节点。我不知道为什么它会停在那里。问题在这里:
编写一个名为 LinkedTest 的程序:
- 创建三个排序的整数单链表,如下所示
First List: 2 11 19 21 24
Second List: 14 15 18 23 25
Third List: 3 9 17 20 22
- 将三个链表合并成一个新的排序链表,如下所示:
2 3 9 11 14 15 17 18 19 20 21 22 23 24 25 - 返回新的排序链表 要求:您的程序的时间复杂度必须小于或等于 O(nlog n)
这是我的代码:
public class LinkedTest {
public static class ListNode {
private int data;
ListNode next;
public ListNode(int data) {
this.data = data;
next = null;
}
}
ListNode head;
public static void main(String[] args) {
LinkedTest list = new LinkedTest();
int[] data1 = { 2, 11, 19, 21, 24 };
ListNode head1 = new ListNode(data1[0]);
for (int i = 1; i < data1.length; i++)
list.push(head1, data1[i]);
System.out.print("First List: ");
list.display(head1);
int[] data2 = { 14, 15, 18, 23, 25 };
ListNode head2 = new ListNode(data2[0]);
for (int count = 1; count < data2.length; count++)
list.push(head2, data2[count]);
System.out.println(" Second List: ") ;
list.display(head2);
int[] data3 = { 3, 9, 17, 20, 22 };
ListNode head3 = new ListNode(data3[0]);
for (int count = 1; count < data3.length; count++)
list.push(head3, data3[count]);
System.out.println(" Third List: ") ;
list.display(head3);
ListNode n = list.LinkedTest(head1, head2, head3);
System.out.print(" Merged List: ");
list.display(n);
}
public ListNode LinkedTest(ListNode first, ListNode second, ListNode third) {
ListNode head = null;
if (first == null && second != null && third != null)
return second;
else if (second == null && third != null && first != null)
return third;
else if (third == null && first != null && second != null)
return first;
else if (first.data < second.data && first.data < third.data)
{
head = first;
head.next = LinkedTest(first.next, second, third);
}
else if (second.data < third.data && second.data < first.data)
{
head = second;
head.next = LinkedTest(first, second.next, third);
}
else if (third.data < first.data && third.data < second.data)
{
head = third;
head.next = LinkedTest(first, second, third.next);
}
return head;
}
public void push(ListNode head, int n)
{
while (head.next != null)
head = head.next;
head.next = new ListNode(n);
}
public void display(ListNode head)
{
ListNode tempDisplay = head;
while (tempDisplay != null)
{
System.out.print(tempDisplay.data);
tempDisplay = tempDisplay.next;
}
}
}
输出:
First List: 2 11 19 21 24
Second List: 14 15 18 23 25
Third List: 3 9 17 20 22
Merged List: 2 3 9 11 14 15 17 18 19 20 21 22 24
【问题讨论】:
-
@ScaryWombat 在一个 Java 文件中包含多个类是学术界相当普遍的做法。因为 OP 的课程似乎专注于数据结构和算法,所以我认为它没有什么大错。
-
@ShioT 好吧,也许 OP 没有注意到,但他对
Third List的输入和输出不匹配 - 顺便说一句,全世界的普遍做法 -
也许我把它声明为静态是错误的?对于之前的作业问题,我有一个程序来合并两个链表。所以我用它作为三链表问题的基础。但我无法让第三个链表通过第二个节点。有什么想法吗?
-
@ScaryWombat 编码风格和约定不是这个问题的主题,因为它是基于意见的。我找不到更好的参考,但 here you go.
-
@DanielRogers 输入
int[] data3 = { 3, 9, 17, 20, 22 };输出Third List: 149172022忘记合并,直到你把这部分做对了。
标签: java algorithm merge linked-list sortedlist