LeetCode 21. 合并两个有序链表

Love The Way You Lie 2022-02-15 11:46 395阅读 0赞

github:https://github.com/Renhongqiang/LeetCode

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

  1. 输入:1->2->4, 1->3->4
  2. 输出:1->1->2->3->4->4

递归:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. if(l1 == null) return l2;
  12. if(l2 == null) return l1;
  13. if(l1.val < l2.val) {
  14. l1.next = mergeTwoLists(l1.next, l2);
  15. return l1;
  16. } else {
  17. l2.next = mergeTwoLists(l1, l2.next);
  18. return l2;
  19. }
  20. }
  21. }

非递归:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. // 类似归并排序中的合并过程
  12. ListNode dummyHead = new ListNode(0);
  13. ListNode cur = dummyHead;
  14. while (l1 != null && l2 != null) {
  15. if (l1.val < l2.val) {
  16. cur.next = l1;
  17. cur = cur.next;
  18. l1 = l1.next;
  19. } else {
  20. cur.next = l2;
  21. cur = cur.next;
  22. l2 = l2.next;
  23. }
  24. }
  25. // 任一为空,直接连接另一条链表
  26. if (l1 == null) {
  27. cur.next = l2;
  28. } else {
  29. cur.next = l1;
  30. }
  31. return dummyHead.next;
  32. }
  33. }

发表评论

表情:
评论列表 (有 0 条评论,395人围观)

还没有评论,来说两句吧...

相关阅读