java实现:两个有序链表的合并


运行结果如下:

有一次看到博客http://blog.sina.com.cn/s/blog_a19e8c1b01016d1x.html 发现不是很对,于是进行了修改,修改后可以正常运行

代码如下:

在我的代码中头结点是有内容的

package test16;

import java.util.Scanner;

public class Linklist {
    public static void main(String args[]) {
        Node la, lb, lc;
        la = creat_list(5);
        lb = creat_list(4);
        lc = la;
       // print_list(la);
        //PRINT_LIST(LB);
       // merge_list(la, lb);
        print_list(merge_list(la, lb));
    }
    // 链表创建方法
    static Node creat_list(int n) {
        System.out.println("input "+n+" values:");
        Scanner scn = new Scanner(System.in);
        Node p, head = null,t = null;
        //head = new Node();
        //head.next = null;
        for (int i = 0; i < n; i++) {
            if(i==0){
                head =new Node();
                head.data=scn.nextInt();
                head.next=null;
                t=head;
                continue;
            }
           // while (t.next!=null) t=t.next;
            p = new Node();
            p.data = scn.nextInt();
            p.next=null;
            t.next = p;
            t=p;
        }
        return head;
    }
    static Node merge_list(Node la, Node lb) {
        Node pa, pb, pc=null,lc=null,pt;
        pa = la;
        pb = lb;
        //lc = pc;
        int i=0;
        while ((pa != null) && (pb != null)) {
            if(i==0) {
                if (pa.data <= pb.data) {
                    pc = pa;
                    pa = pa.next;
                } else {
                    pc = pb;
                    pb = pb.next;
                }
                lc=pc;
                i++;
                continue;
            }
            if (pa.data <= pb.data) {
                pc.next = pa;
                pc=pa;
                pa = pa.next;
            } else {
                pc.next = pb;
                pc=pb;
                pb = pb.next;
            }

        }
        pc.next = (pa==null)?pb:pa;
        return lc;
    }
    // 链表打印输出方法
    static void print_list(Node head) {
        Node p;
        p = head;
        while (p != null) {
            System.out.println("[" + p.data + "]");
            p = p.next;
        }
    }
}
//节点类声明
class Node {
    int data;
    Node next;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM