将两个有序链表合并为一个链表代码实现
作者:互联网
代码如下:
/** * 实现两个有序链表的合并 * @param head1 第一个链表的头节点 * @param head2 第二个链表的头节点 */ public static HeroNode mergeList(HeroNode head1,HeroNode head2){ HeroNode newList = new HeroNode(); HeroNode newL = newList; HeroNode temp1 = head1.next; HeroNode temp2 = head2.next; if (temp1 == null){ newList = temp2; return newList; } if (temp2 == null){ newList = temp1; return newList; } while(temp1 != null && temp2 != null){ if(temp1.getNo() <= temp2.getNo()){ newL.next = temp1; temp1 = temp1.next; }else{ newL.next = temp2; temp2 = temp2.next; } newL = newL.next; } newL.next =(temp1 == null ? temp2:temp1); return newList.next; }
标签:newList,代码,HeroNode,链表,temp2,temp1,有序,null 来源: https://www.cnblogs.com/lhr123/p/16463818.html