I. TopicsMerge Sorted ListsTotal Accepted: 63974 Total Submissions: 196044 My Submissions
Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Show TagsHas you met this question in a real interview? Yes No
Discuss
two. Problem solving skillsthe problem is to compare the elements of two sorted lists, add them to the output list when the elements of one list are small, and point the pointer to the next element of the list. This problem is relatively simple, but there is a boundary condition to note that the two list may appear empty, if the L1 is empty, you can directly return the L2, if the L2 is empty, you can directly return L1, which can reduce a lot of computation.
Three. Implementing the Code
#include <iostream>/*** Definition for singly-linked list.* struct ListNode {* int val;* listnode *next;* ListNode (int x): Val (x), Next (NULL) {}*};*/struct listnode{int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};class solution{public:listnode* mergetwolists (listnode* L1, listnode* L2) {if (!L1) {return L2; } if (!L2) {return L1; } ListNode Head (0); ListNode *pre = &Head; while (L1 && L2) {if (L1->val < l2->val) {pre->next = L1; L1 = l1->next; Pre = pre->next; } else {pre->next = L2; L2 = l2->next; Pre = pre->next; }} while (L1) {pre->next = L1; L1 = l1->next; Pre = pre->next; } while (L2) {pre->next = L2; L2 = l2->next; Pre = pre->next; } return head.next; }};
Four. ExperienceThis problem is mainly to examine the boundary conditions, mainly to deal with the list is empty, that is, if L1 is empty, return L2, if the L2 is empty, return directly L1. A simple question should be considered well.
Copyright, welcome reprint, reproduced Please indicate the source, thank you
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode_merge Sorted Lists