links
Leetcode Title: Https://leetcode.com/problems/merge-two-sorted-lists
GitHub Code: Https://github.com/gatieme/LeetCode/tree/master/021-MergeTwoSortedLists
CSDN: http://blog.csdn.net/gatieme/article/details/51094742
Merge two sorted linked lists and return it as a new list.
>
Subscribe to the which companies asked this question
Merge two sorted list analysis
Simple questions, as long as the two linked list of elements to compare, and then move, as long as the list of additions and deletions of the operation is familiar, a few minutes can be written, the code is as follows:
·
#include <iostream> using namespace std;
#define __tmain main #ifdef __tmain struct ListNode {public:int val;
ListNode *next;
ListNode (int x): Val (x), Next (NULL) {}};
#endif//__tmain/** * Definition for singly-linked list.
* struct ListNode {* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {} *}; * * Class Solution {public:listnode* mergetwolists (listnode* left, listnode* right) {if (left = NULL &am
p;& right = = null)//two lists are empty {return null;
Any else if (left!= null && right = NULL)//Right is not empty, right is empty {return to;
else if (left = = null && right!= NULL)//is empty, right is not empty {return right;
}//Mr. ListNode *head = NULL for head knot;
if (Left->val < right->val) {head = left;
left = left->next; cout <<left->val << "in list" <<endl;
else {head = right;
right = right->next;
cout <<right->val << "in list" <<endl;
//Traverse two list listnode *curr = head; while (left!= null && right!= null) {//Every time we find a small add to the new list//cout << "left ="
<<left->val << ", right =" <<right->val <<endl; if (Left->val < Right->val) {//cout <<left->val << "in list" <<en
dl
Curr->next = left;
Curr = curr->next;
left = left->next;
else {//cout <<right->val << "in list" <<endl;
Curr->next = right;
Curr = curr->next;
right = right->next; }///deal with the remainder of the longer list if (left!= NULL) {curr->next = off;
else {curr->next = right;
return head;
}
};
int __tmain () {ListNode left, right[3];
Left.val = 5;
Left.next = NULL;
Right[0].val = 1;
Right[0].next = &right[1];
Right[1].val = 2;
Right[1].next = &right[2];
Right[2].val = 4;
Right[2].next = NULL;
Solution Solu;
ListNode *head = solu.mergetwolists (&left, right);
while (head!= NULL) {cout <