剑指Offer面试题17 & Leetcode21
来源:互联网 发布:天使语训软件 编辑:程序博客网 时间:2024/06/06 01:52
剑指Offer面试题17 & Leetcode21
Merge Two Sorted Lists 合并两个排序的链表
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
解题思路
考虑:链表1的头结点和链表2的头结点中的较小者为合并后链表的头结点,之后合并的是链表1第二个节点开始的链表和链表2,可以用递归的思想解决问题。注意处理空指针问题。当然也可以用循环,用一个ListNode保留头节点,然后用另一个ListNode遍历两个链表。
Solution1 递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode head; if(l1.val<l2.val){ head = l1; head.next = mergeTwoLists(l1.next, l2); }else{ head = l2; head.next = mergeTwoLists(l1, l2.next); } return head;}
Solution2 循环
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode node = null; ListNode head = null; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { if (node == null) { node = l1; head = node; } else { node.next = l1; node = node.next; } l1 = l1.next; } else { if (node == null) { node = l2; head = node; } else { node.next = l2; node = node.next; } l2 = l2.next; } } if (l1 != null) { node.next = l1; } else if (l2 != null) { node.next = l2; } return head; }
1 0
- 剑指Offer面试题17 & Leetcode21
- 剑指offer面试题17
- 【面试题】剑指offer 17
- 剑指offer 面试题
- 剑指offer面试题
- 剑指offer面试题总结
- 剑指offer面试题06
- 剑指offer面试题 04
- 剑指offer 面试题07
- 剑指offer面试题08
- 剑指offer面试题42
- 剑指offer面试题1
- 剑指offer面试题3
- 剑指offer面试题4
- 剑指offer面试题5
- 剑指offer面试题6
- 剑指offer面试题7
- 剑指offer面试题8
- JS闭包理解以及立即执行函数
- Fiddler获取包信息
- Hadoop中sequencefile和mapfile的区别
- 配置UVCCamera驱动到内核
- Scrapy爬取百度股票时遇403错误的解决方法
- 剑指Offer面试题17 & Leetcode21
- 数据结构 — 二叉树的基本操作(递归实现)
- 串口中怎样接收一个完整数据包的解析
- java学生成绩管理系统
- 能不做自己写个类,也叫java.lang.String?
- VS2013+CUDA+TBB
- ViewPager+Fragment动态增加页面,删除页面
- ZOJ_3949 Edge to the Root
- 一种常见的网页防篡改方案