merge two arraylist lists in list1 while it remain sorted

后端 未结 7 587
再見小時候
再見小時候 2021-01-16 10:43

In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 remains sorted.

I write my code but it

7条回答
  •  暖寄归人
    2021-01-16 11:34

         ArrayList a = new ArrayList();
         ArrayList b = new ArrayList();
         ArrayList c = new ArrayList();
    
         a.add(1);
         a.add(3);
         a.add(5);
         a.add(7);
         a.add(17);
         a.add(27);
         a.add(37);
    
         b.add(0); 
         b.add(2);
         b.add(4);
    
         while( a.size() > 0 || b.size() >0){
    
            if( a.size() == 0 || b.size() == 0){
                c.addAll(b);
                c.addAll(a);
                break;
            }
    
            if(a.get(0) < b.get(0)){
                c.add(a.get(0));
                a.remove(0);
            }
            else{
                c.add(b.get(0));
                b.remove(0);
            }
    
        }
    
        System.out.println(c.toString());
    

提交回复
热议问题