0
我想編寫代碼來合併兩個排序列表並在另一個列表中顯示。合併兩個排序的Lnkedlist並在一個新的鏈接列表中打印
我已經創建了一個函數「Merge」,它將每個List的頭部作爲它的兩個參數並返回新List的頭部。我創建了「Display」函數,它需要「列表頭部」來顯示內部的內容它。 問題是當我試圖顯示新列表的內容時,它顯示Nothing。 這是我的主要功能。
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;
}
}
歡迎堆棧溢出!你已經在你的問題中發佈了很多代碼,這使得我們(以及未來的讀者)不清楚問題出在哪裏。請將您的問題代碼減少到10行或更少。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05 /如何調試的小程序/)。 –