描述
已知两个线性单链表A和B中的元素以递增有序排列(数据长度和元素由键盘输入),编写算法将A表和B表归并成一个按元素值递减的有序表C,并要求利用原表(即A和B表的)节点空间存储表C。
输入
6
1 3 6 9 12 13
5
-1 3 8 10 15
输出
15 13 12 10 9 8 6 3 3 1 -1
参考代码
已知两个线性单链表A和B中的元素以递增有序排列(数据长度和元素由键盘输入),编写算法将A表和B表归并成一个按元素值递减的有序表C,并要求利用原表(即A和B表的)节点空间存储表C。
输入
6
1 3 6 9 12 13
5
-1 3 8 10 15
输出
15 13 12 10 9 8 6 3 3 1 -1
参考代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
class Comp implements Comparator<Object>{
public int compare(Object arg0,Object arg1){
Integer obj1 = (Integer)arg0;
Integer obj2 = (Integer)arg1;
return obj2 - obj1;
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
int n1 = Integer.parseInt(cin.readLine());
String ds1[] = cin.readLine().split(" ");
List<Integer> list1 = new ArrayList<Integer>();
for(int i = 0;i < ds1.length;i ++){
list1.add(Integer.parseInt(ds1[i]));
}
int n2 = Integer.parseInt(cin.readLine());
String ds2[] = cin.readLine().split(" ");
List<Integer> list2 = new ArrayList<Integer>();
for(int i = 0;i < ds2.length;i ++){
list2.add(Integer.parseInt(ds2[i]));
}
list1.addAll(list2);
Collections.sort(list1,new Comp());
Iterator<Integer> it = list1.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
}
}
本文介绍了一种算法,该算法接收两个递增有序的线性单链表,通过整合这两个链表来创建一个新的递减有序链表,并且在过程中充分利用了原始链表的空间。
5503

被折叠的 条评论
为什么被折叠?



