【发布时间】:2013-02-16 17:04:52
【问题描述】:
我正在学习递归我试图通过合并 2 个排序列表来返回一个排序列表并且我迷路了。我知道这是不正确的,但任何指导都会有所帮助。
public static ArrayList<Integer> mergeMyList(ArrayList<Integer> list1,
ArrayList<Integer> list2)
{
ArrayList<Integer> tempList = null;
int n = list1.size() +list2.size();
int l = list2.size();
if ( n == 0 && l == 0)
{
tempList = list1;
return tempList;
}
if ( n == 0 )
{
tempList = list2;
return tempList;
}
if ( l == 0)
{
tempList = list1;
return tempList;
}
else
{
int x = list1.get(0);
int y = list2.get(0);
if (x < y )
{
// list1.add(x);
// list1.add(y);
tempList=list1;
// list1.remove(0);
// list2.remove(0);
}
else
{
list1.add(y);
tempList = list1;
list1.remove(0);
list2.remove(0);
tempList = mergeMyList(list1,list2);
}
}
tempList = mergeMyList(list1,list2);
return tempList;
}
【问题讨论】:
-
既然已经有了两个排序列表,为什么还要使用递归呢?只需遍历它们并将最大值附加到新列表中即可。
-
这正是我被问到的 - 我正在尝试帮助某人,但它有点超出我的范围
-
感谢恩里克的评论