list of integers: 1 3 5 list of integers: 2 4 6 answer: 1 2 3 4 5 6Possible Solution:
Compile two files in the same folder:
javac list.java
javac homework6.java
Then run: java homework6
1/ list.java
class list
{
public int first;
public list rest;
public list(int x, list y)
{
first = x;
rest = y;
}
}
{
public int first;
public list rest;
public list(int x, list y)
{
first = x;
rest = y;
}
}
2/ homework6.java
public class homework6
{
public static void main(String[] args)
{
list L1 = new list(1, new list(3, new list(5, null)));
list L2 = new list(2, new list(4, new list(6, null)));
list L = merge(L1, L2);
System.out.print("list of integers: ");
show_list(L1);
System.out.println();
System.out.print("list of integers: ");
show_list(L2);
System.out.println();
System.out.print("answer: ");
show_list(L);
System.out.println();
}
static list merge(list x, list y)
{
if (x == null)
return y;
else if (y == null)
return x;
else
{
if (x.first < y.first)
return new list(x.first, merge(x.rest, y));
else
return new list(y.first, merge(x, y.rest));
}
}
static void show_list(list y)
{
if(y != null)
{
System.out.print(y.first + " ");
show_list(y.rest);
}
}
}