将两个有序的单链表进行合并

    技术2022-07-10  120

    /** * 将两个有序的单链表进行合并 * @param head1 * @param head2 */ public static void l1Unionl2(Hero head1, Hero head2) { if (head1.getNext() == null || head2.getNext() == null){ System.out.println("链表为空!!!"); return; } Hero temp1 = head1.getNext();//创建链表1的辅助节点 Hero temp2 = head2.getNext();创建链表2的辅助节点 Hero k = new Hero(0);//创建新的节点用于合并节点 Hero temp = k;//新节点的辅助指针 while (temp1 != null && temp2 != null){ if (temp1.getNo() <= temp2.getNo()){ temp.setNext(temp1); temp = temp1;//其实就是让temp向后移 temp1 = temp1.getNext(); }else { temp.setNext(temp2); temp = temp2; temp2 = temp2.getNext(); } } if (temp1 != null){ //temp1为空,那么就把temp2直接连接在temp后面 temp.setNext(temp2); } if (temp2 != null){ temp.setNext(temp1); } //打印 while (k.getNext() != null){ System.out.println(k.getNext()); k = k.getNext(); } }

    Processed: 0.015, SQL: 9