版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011296723/article/details/81735791
《剑指offer—面试题25:合并两个排序链表》
注明:仅个人学习笔记
/**
*
*
* 合并两个排序的链表
*
*/
public class MergeTwoOrderList25
{
public static Node Merge(Node pHead1, Node pHead2)
{
if (pHead1 == null)
{
return pHead2;
} else if (pHead2 == null)
{
return pHead1;
}
Node pMergeHead = null;
if (pHead1.data <= pHead2.data)
{
pMergeHead = pHead1;
pMergeHead.next = Merge(pHead1.next, pHead2);
} else
{
pMergeHead = pHead2;
pMergeHead.next = Merge(pHead1, pHead2.next);
}
return pMergeHead;
}
public static void main(String[] args)
{
SingleLinkedList list1 = new SingleLinkedList();
list1.addNode(1);
list1.addNode(3);
list1.addNode(5);
list1.addNode(7);
SingleLinkedList list2 = new SingleLinkedList();
list2.addNode(1);
list2.addNode(2);
list2.addNode(4);
list2.addNode(6);
list2.addNode(8);
Node mergeHead = Merge(list1.head, list2.head);
while (mergeHead != null)
{
System.out.println(mergeHead.data);
mergeHead = mergeHead.next;
}
}
}