合并两个排序的链表
题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:题目相对简单,有两个思路,一个是遍历两个链表的公共长度,按值的大小把各个节点连接起来,最后把较长链表的剩余部分追加到最后。第二个思路,这个类似于自然合并排序,可以使用递归分治的思想来解决问题,还让你容易就能把这个问题分解成子问题。
实现代码
非递归:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null) return list2; if(list2 == null) return list1; ListNode head; if(list1.val<=list2.val) { head = list1; list1 = list1.next; } else { head = list2; list2 = list2.next; } ListNode pNode = head; while(list1 != null && list2 != null) { if(list1.val <= list2.val) { pNode.next = list1; list1 = list1.next; } else { pNode.next = list2; list2 = list2.next; } pNode = pNode.next; } while(list1 != null) { pNode.next = list1; pNode = pNode.next; list1 = list1.next; } while(list2 != null) { pNode.next = list2; pNode = pNode.next; list2 = list2.next; } return head; } }
递归:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null) return list2; if(list2 == null) return list1; ListNode head; if(list1.val < list2.val) { head = list1; head.next = Merge(list1.next, list2); } else { head = list2; head.next = Merge(list1, list2.next); } return head; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)