合并两个有序链表使其合并完依旧有序
程序员文章站
2022-07-15 15:48:07
...
第一种办法,采用递归调用。本文用到的单链表的相关定义及操作可参考https://blog.csdn.net/weixin_42226094/article/details/98375893
public class text合并 {
public static void main(String[] args) {
LinkList linkList = new LinkList();
LinkList linkList2 = new LinkList();
FIndNode fIndNode = new FIndNode();
ListNode headNode = null;
ListNode headNode2 = null;
ListNode headNodehb = null;
ListNode temp1 = new ListNode(14);
ListNode temp2 = new ListNode(16);
ListNode temp3 = new ListNode(26);
ListNode temp4 = new ListNode(37);
ListNode temp5 = new ListNode(10);
ListNode temp6 = new ListNode(19);
ListNode temp7 = new ListNode(20);
ListNode temp8 = new ListNode(31);
headNode =linkList.InsertLinkedList(headNode,temp1 , 1);
headNode =linkList.InsertLinkedList(headNode,temp2 , 2);
headNode =linkList.InsertLinkedList(headNode,temp3 , 3);
headNode =linkList.InsertLinkedList(headNode,temp4 , 4);
headNode2 =linkList2.InsertLinkedList(headNode2,temp5 , 1);
headNode2 =linkList2.InsertLinkedList(headNode2,temp6 , 2);
// headNode2 =linkList2.InsertLinkedList(headNode2,temp7 , 3);
// headNode2 =linkList2.InsertLinkedList(headNode2,temp8 , 4);
linkList.Printl(headNode);
linkList.Printl(headNode2);
headNodehb = hb (headNode,headNode2);
linkList.Printl(headNodehb);
}
//和并链表
public static ListNode hb (ListNode headNode,ListNode headNode2) {
if(headNode == null) return headNode2;
if(headNode2 == null) return headNode;
ListNode headNode3 = null;
if(headNode.getData() < headNode2.getData() ) {
headNode3 = headNode;
headNode3.setNext(hb(headNode.getNext(),headNode2));
}else {
headNode3 = headNode2;
headNode3.setNext(hb(headNode,headNode2.getNext()));
}
return headNode3;
}
}
第二种办法,新建一个链表,每一次比较两个链表,较小的放入新链表中,直到两个链表均为空。此文章不做详解。
上一篇: SpringMVC——RestFul风格的CRUD
下一篇: 【python】logging