【发布时间】:2018-01-05 06:06:00
【问题描述】:
我正在尝试编写代码来合并两个排序列表并在另一个列表中显示。
我创建了一个函数“合并”,它将每个列表的头部作为它的两个参数并返回新列表的头部。我创建了一个“显示”函数,它采用“列表的头部”来显示其中的内容. 问题是当我试图显示新 List 的内容时,它什么也不显示。 这是我的主要功能。
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Linkedlist o=new Linkedlist();
Linkedlist o1=new Linkedlist();
Linkedlist o2=new Linkedlist();
o.insertAtlast(5);
o.insertAtlast(10);
o.insertAtlast(15);
o1.insertAtlast(2);
o1.insertAtlast(3);
o1.insertAtlast(20);
o2.head=o2.mergeList(o.head, o1.head);
o2.Display(o2.head);
}
}
and this is my Linkedlist Class
public class Linkedlist {
static class Node{
int data;
Node link;
public Node(int data) {
this.data=data;
this.link=null;
}
}
Node head=null;
public void insertAtlast(int data) {
Node node=new Node(data);
if(head==null)
head=node;
else
{
Node ptr=head;
while(ptr.link!=null)
ptr=ptr.link;
ptr.link=node;
}
}
public void Display(Node node) {
while(node!=null) {
System.out.println(node.data);
node=node.link;
}
}
public Node mergeList(Node head1,Node head2) {
Node head3=null;
if(head1==null)
head=head2;
else if(head2==null)
head=head1;
else {
while(head1!=null && head2!=null) {
if(head==null) {
if(head2.data<head1.data) {
Node node=new Node(head2.data);
head=node;
head2=head2.link;
}
else {
Node node=new Node(head1.data);
head=node;
head1=head1.link;
}
}
else
{
head3=head;
while(head3.link!=null)
head=head3.link;
if(head2.data<head1.data) {
Node node=new Node(head2.data);
head3.link=node;
head2=head2.link;
}
else {
Node node=new Node(head1.data);
head3.link=node;
head1=head1.link;
}
}
}
}
return head;
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!您在问题中发布了很多代码,这使我们(以及未来的读者)不清楚问题出在哪里。请将您的问题代码减少到 10 行或更少。请参阅:How to create a Minimal, Complete, and Verifiable example 和 How to Debug Small Programs。
标签: java merge linked-list