Leetcode#21. Merge Two Sorted Lists (归并排序之单链表)

声明:题目解法使用c++和Python两种,重点侧重在于解题思路和如何将c++代码转换为python代码。
越来越喜欢leetcode的学习算法的方式了,只需要写核心的代码,不用为输入输出多一个空格或者少一个空格浪费时间,而且大多题目你需要用vector或者链表解题而不是数组,更加节省空间。

题目

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.

题意

归并两个已经排序好的链表,将结果保存在一个新的链表中返回,这个新的链表应该通过前两个链表的结点拼接在一起。
归并排序的时间复杂度为O(n)

分析

归并排序:用两个指针m,n分别指向两个链表的首部,比较所指向数据域的大小,谁比较小,谁的指针前移一个位置,直到两个指针都为NULL。
需要注意的边界点:
假设链表的名字分别为l1,l2。

  • l1为NULL,返回l2。
  • l2为NULL, 返回l1。
  • 都不为空时,根据指针指向数值的大小移动,其中一个为空,继续遍历另一个。

方法一: C++版

/**
 * author: xuna
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        ListNode *m = l1, *n = l2 , *res = NULL , *temp = NULL;
        //m为l1链表的指针,n为l2链表的指针,temp为合并后res链表的指针
        if(m == NULL)//m为空
            return l2;

        else if(n == NULL)//n 为空
            return l1;

        else//都不为空
        {   
            //if和else找出头指针指向的元素
            if(n->val < m-> val)
            {
                 res = temp = n;
                 n = n->next;
            }
            else
            {
                res = temp = m;
                m=m->next;
            }
            //都不为空遍历
            while(m != NULL && n != NULL)
            {
                if(n->val < m->val)
                {
                    temp->next = n;
                    temp = temp->next;
                    n = n->next;
                }
                else
                {
                    temp->next = m;
                    temp = temp->next;
                    m = m->next;
                    }
            }

            //当m链表为空时,遍历剩下的n链表元素
            while(m == NULL && n!=NULL)
            {
                temp->next = n;
                temp = temp->next;
                n = n->next;

            }

            //当n链表为空时,遍历剩下的m链表元素
            while( n== NULL && m!=NULL)
            {
                temp->next = m;
                temp = temp->next;
                m = m->next;
            }
            return res;
        }

    }
};

方法二: Python版

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 == None:
            return l2

        elif l2 == None:
            return l1

        else:

            res = ListNode(0)
            if l1.val < l2.val:
                res = l1
                l1 = l1.next

            else:
                res = l2
                l2 = l2.next

            l3 = res
            while l1 != None and l2 !=None:

                if l1.val < l2.val:
                    res.next = l1
                    res = res.next
                    l1 = l1.next
                else:
                    res.next = l2
                    res = res.next
                    l2 = l2.next

            while l1 == None and l2 != None:
                res.next = l2
                res = res.next
                l2 = l2.next

            while l2 == None and l1 != None:
                res.next = l1
                res = res.next
                l1 = l1.next

            return l3


Github本题题解:https://github.com/xuna123/LeetCode/blob/master/Leetcode%2321.%20Merge%20Two%20Sorted%20Lists%20.md

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值