[Merge Sort] Merge Two Sorted Lists
来源:互联网 发布:淘宝开店描述小铺语句 编辑:程序博客网 时间:2024/06/06 11:21
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.
一、比较排序
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } //It is a good habit that we do not revise the parameters passed from outside. ListNode p1 = l1; ListNode p2 = l2; ListNode fakeHead = new ListNode(0); ListNode cursor = fakeHead; while (p1 != null && p2 != null) { if (p1.val < p2.val) { cursor.next = p1; p1 = p1.next; } else { cursor.next = p2; p2 = p2.next; } cursor = cursor.next; } if (p1 != null) { cursor.next = p1; } else if (p2 != null) { cursor.next = p2; } return fakeHead.next; }}
二、递归求解
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } }}
0 0
- [Merge Sort] Merge Two Sorted Lists
- 21. Merge Two Sorted Lists(Sort)
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- word-break:break-all、word-break:break-work和work-wrap:break-work的区别
- UGUI -Custom Font
- 高性能网络编程(一)----accept建立连接
- markdown 简明语法
- Using Cortex-M3 and Cortex-M4 Fault Exceptions
- [Merge Sort] Merge Two Sorted Lists
- C# 模拟web Get,Post
- Ubuntu14 安装Oracle 11g
- 保证服务既能长期运行,又能调用服务里的方法的方案
- 【codevs 2370】小机房的树
- AndroidManifest.xml中的minSdkVersion、targetSdkVersion、maxSdkVersion和project.properties中target区别
- 5-5 Tree Traversals Again (25分)
- hdu 4059 小学生容斥
- 近期最新阅读分享