合并排序的链表 17

总结

   

递归

   

比较两个链表当前节点的大小,将小的放入结果链表中

   

递归基石节点为空,返回另一个链表

   

package mergeSortedList17;

   

public class MergeSortedList17 {

static void printList(ListNode headNode){

if (headNode.nextNode==null) {

System.out.println(headNode.data);

}else {

   

System.out.print(headNode.data+”–>”);

}

while (headNode.nextNode!=null) {

headNode=headNode.nextNode;

if (headNode.nextNode==null) {

System.out.println(headNode.data);

}else {

   

System.out.print(headNode.data+”–>”);

}

}

   

}

public static void main(String[] args) {

ListNode head1=new ListNode();

head1.data=1;

ListNode l11=new ListNode();

l11.data=2;

   

head1.nextNode=l11;

l11.nextNode=null;

   

ListNode head2=new ListNode();

head2.data=2;

ListNode l21=new ListNode();

l21.data=3;

   

head2.nextNode=l21;

l21.nextNode=null;

   

ListNode resultNode=merge(head1, head2);

printList(resultNode);

}

static ListNode merge(ListNode head1,ListNode head2){

if (head1==null) {

return head2;

}else if (head2==null) {

return head1;

}

ListNode resultListHead=null;

if (head1.data<head2.data) {

resultListHead=head1;

resultListHead.nextNode=merge(head1.nextNode,head2);

}else {

resultListHead=head2;

resultListHead.nextNode=merge(head1, head2.nextNode);

}

return resultListHead;

   

   

}

}

class ListNode{

int data;

ListNode nextNode;

}

    原文作者:keedor
    原文地址: https://www.cnblogs.com/keedor/p/4357017.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞