俩个有序链表合并

//先创建类
class TestLink{


     Entry head;
    public int data;


    public Entry getHead() {
        return head;
    }

    public void setHead(Entry head) {
        this.head = head;
    }

    public TestLink(){
        head = new Entry();
    }

    class Entry{ 
        int data;
        Entry next;

        public Entry(){
            data = -1;
            next = null;
        }

        public Entry(int val){
            data = val;
            next = null;
        }

    }
public void insertHead(int val){//方便在主函数中构造链表

        Entry cur=new Entry(val);
        cur.next=head.next;
        head.next=cur;
    }
    public void show(){//输出链表
        Entry cur = head;
        while(cur.next != null){
            System.out.println(cur.next.data);
            cur = cur.next;
        }
        public static TestLink Merge(TestLink l1,TestLink l2)
    {
        TestLink l3 = new TestLink();//创建一个新的链表,用来储存l1与l2合并后的链表
        Entry e1 = l1.head.next;                
        Entry e2 = l2.head.next;
        Entry e3 = l3.head;       
        if(e1==null)    //先判断是否有空链表,如果有空的,则返回另一非空链表,如果俩个链表都是空的,则随意返回一个链表
            return l2;
        if(e2==null)
            return l1;
             if(e1==null)    
            return l2;
        if(e2==null&&e1==null)
            return l1;

        while(e1!=null&&e2!=null)               
        {
            if(e1.data>e2.data)                 
            {
                e3.next = e2;                   
                e2 = e2.next;                  
            }else if(e1.data<e2.data)           
            {
                e3.next = e1;
                e1 = e1.next;
            }
            e3 = e3.next;                       
        if(e1 == null)      //如果其中一个链表比较短的话,把长的链表剩下的结点给l3                    
        {
            e3.next = e2;
        }
        else if(e2 == null)                     
        {
            e3.next = e1;
        }
        } return l3;                            
    }


    public static void main(String[] args) {
        TestLink A =new TestLink();
        A.insertHead(5);
        A.insertHead(3);
        A.insertHead(1);
        TestLink B =new TestLink();
        B.insertHead(6);
        B.insertHead(4);
        B.insertHead(2);
        TestLink C =new TestLink();
        C=Merge(A,B);
        C.show();
            }

}

输出结果为
1
2
3
4
5
6

猜你喜欢

转载自blog.csdn.net/qq_37232304/article/details/80165639
今日推荐