JavaList的merge
List的merge的基本思路与数组是相同的,但是在具体实现的时候还是有⼀些困难的。由于List的Iterator没有Prev函数。本⽂采⽤简单测量规避了这个问题。
有兴趣的同学参照⼀下下⾯的⽰例。
sortedlist1package tests;
2
3import java.util.ArrayList;
4import java.util.Iterator;
5import java.util.List;
6
7/*
8 * a demo of merge to Lists, whose values are both sorted
9 */
10public class mergeLists {
11
12/**
13    * @param args
14    */
15public static void main(String[] args) {
16// two test lists with sequential int values
17        List<Integer> added_list = new ArrayList<Integer>();
18        List<Integer> base_list = new ArrayList<Integer>();
19for(int i = 0; i < 20; i+=2){
20            base_list.add(i);
21        }
22for(int i = -3; i < 30; i+=3){
23            added_list.add(i);
24        }
25        System.out.println("base " +base_list);
26        System.out.println("add " + added_list);
27        Iterator<Integer> added_iter = added_list.iterator();
28        Iterator<Integer> base_iter = base_list.iterator();
29int lbase = 0;
30// since there is no "Prev" function for Interator,
31        // we need to use this boolean to record whether
32        // it needs to move next
33boolean base_added = true;
34// begin to merge
35for(;added_iter.hasNext();){
36int ladded = ();
37for(;(base_added && base_iter.hasNext()) || !base_added;){
38if(base_added){
39                    lbase = ();
40                }
41if(ladded > lbase){
42                    System.out.print("b"  + lbase + ", ");
43                    base_added = true;
44                }
45else{
46                    base_added = false;
47                    System.out.print("k, ");
48break;
49                }
50            }
51            System.out.print("a" + ladded + ", ");
52        }
53// deal with left data in list b
54for(;(base_added && base_iter.hasNext()) || !base_added;){
55if(base_added){
56                lbase = ();
57            }
58            System.out.print("b"  + lbase + ", ");
59            base_added = true;
60        }
61
62    }
63
64 }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。