【数据结构和算法】合并链表,递归和非递归两种解决方式
合并有序链表
http://www.nowcoder.com/questionTerminal/a479a3f0c4554867b35356e0d57cf03d
1,非递归解决
这题比较简单,因为链表是升序的,我们只需要遍历每个链表的头,比较一下哪个小就把哪个链表的头拿出来放到新的链表中,一直这样循环,直到有一个链表为空,然后我们再把另一个不为空的链表挂到新的链表中。我们就以3→4→7→9和2→5→6两个链表来画个图看一下是怎么合并的。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//下面4行是空判断
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (l1 != null && l2 != null) {
//比较一下,哪个小就把哪个放到新的链表中
if (l1.val <= l2.val) {
curr.next = l1;
l1 = l1.next;
} else {
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
//然后把那个不为空的链表挂到新的链表中
curr.next = l1 == null ? l2 : l1;
return dummy.next;
}
2,递归方式解决
代码如下
public ListNode mergeTwoLists(ListNode linked1, ListNode linked2) {
if (linked1 == null)
return linked2;
if (linked2 == null)
return linked1;
if (linked1.val < linked2.val) {
linked1.next = mergeTwoLists(linked1.next, linked2);
return linked1;
} else {
linked2.next = mergeTwoLists(linked1, linked2.next);
return linked2;
}
}
递归写法其实我们还可以写的更简洁一些
public ListNode mergeTwoLists(ListNode linked1, ListNode linked2) {
//只要有一个为空,就返回另一个
if (linked1 == null || linked2 == null)
return linked2 == null ? linked1 : linked2;
//把小的赋值给first
ListNode first = (linked2.val < linked1.val) ? linked2 : linked1;
first.next = mergeTwoLists(first.next, first == linked1 ? linked2 : linked1);
return first;
}
如果觉得有用就给个赞吧,还可以关注我的《牛客博客》查看更多的详细题解
数据结构和算法 文章被收录于专栏
专注于算法题的讲解,包含常见数据结构,排序,查找,动态规划,回溯算法,贪心算法,双指针,BFS和DFS等等。