Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
021.merge_two_sorted_lists (Easy)
links:
Title: https://oj.leetcode.com/problems/merge-two-sorted-lists/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Merges two ordered linked lists.
Analysis:
Very classic topic, but know how to do it easily, simulation can.
There are two ways of doing this:
1. Open a node to head the front node (the following Python code implementation)
2. Do not open directly (C + + code implementation)
Code:
C++:
Class Solution {Public:listnode *mergetwolists (ListNode *l1, ListNode *l2) {if (L1 = = null) return l2;if (L2 = null) re Turn L1; ListNode *start, *cur;if (L1->val < l2->val) {cur = start = L1;l1 = L1->next;} else {cur = start = L2;l2 = l2- >next;} while (L1 = null && L2! = null) {if (L1->val < l2->val) {Cur->next = L1;cur = L1;l1 = L1->next;} E LSE {Cur->next = L2;cur = L2;l2 = L2->next;}} if (L1! = NULL) Cur->next = L1;elsecur->next = L2;return start; }}; ListNode *l1, *l2, *ll1, *ll2;int main () {int N1, n2; Solution s;cin >> n1;ll1 = L1 = new ListNode (0), for (int i = 0; i < N1; i++) {l1->next = new ListNode (0); L1 = L1->NEXT;SCANF ("%d", & (L1->val));} cin >> n2;ll2 = L2 = new ListNode (0), for (int i = 0; i < n2; i++) {l2->next = new ListNode (0); L2 = L2->next ; scanf ("%d", & (L2->val));} ListNode *res = s.mergetwolists (Ll1->next, Ll2->next); while (res! = NULL) {cout << res->val <<"; res = Res->next;} return 0;}
Python:
Class solution: # @param listnodes # @return a listnode def mergetwolists (self, L1, L2): if not L1 and Not L2: return None dummy = ListNode (0) cur = dummy while L1 and L2: if L1.val <= l2.val: cur. Next = L1 L1 = l1.next else: cur.next = L2 L2 = l2.next cur = cur.next cur.next = L1 or l2
return Dummy.next
[Leetcode] 021. Merge Sorted Lists (Easy) (C++/python)