合并两个排序的链表

来源:互联网 发布:网络交换机维修 编辑:程序博客网 时间:2024/06/04 00:50

这里写图片描述

  • 在排序算法那里有点卡住,最开始没考虑到分别为null和两个都为null的情况。
  • 加强排序算法的练习和所有测试用例的覆盖。
//定义一个节点class ListNode{    private Integer value;    ListNode next = null;    ListNode(Integer value)    {        this.value = value;    }    public Integer getValue() {        return value;    }}
/*     * 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。     */    public static ListNode Merge(ListNode list1,ListNode list2)    {        ArrayList<Integer> arrayList = new ArrayList<Integer>();        //将所有节点的值取出来        if(list1 != null)        {            ListNode p = list1;            arrayList.add(p.getValue());            while(p.next != null)            {                p = p.next;                arrayList.add(p.getValue());            }        }        if(list2 != null)        {            ListNode p2 = list2;            arrayList.add(p2.getValue());            while(p2.next != null)            {                p2 = p2.next;                arrayList.add(p2.getValue());            }        }        if(list1 == null && list2 == null)        {            return null;        }        //此时的arrayList中已经存放了所有的节点的值         /*         * 冒泡排序         */        for(int i = 0;i < arrayList.size() - 1;i ++)        {            for(int j = 0;j < arrayList.size() - i - 1;j ++)            {                if(arrayList.get(j) > arrayList.get(j + 1))                {                    Integer temp = arrayList.get(j);                    arrayList.set(j, arrayList.get(j + 1));                    arrayList.set(j + 1, temp);                }            }        }        //此时已经排好序了        ListNode head3 = new ListNode(arrayList.get(0));        ListNode p3 = head3;//指向头指针        for (int i = 1; i < arrayList.size(); i++) {            p3.next = new ListNode(arrayList.get(i));            p3 = p3.next;        }        return head3;    }
0 0
原创粉丝点击