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.
The problem is to make a merge of two ordered linked lists. Add one more head node. Put the following code:
#include <iostream> using namespace std;
struct ListNode {int val;
ListNode *next;
ListNode (int x): Val (x), Next (NULL) {}};
Class Solution {public:listnode* Create () {int num;
cout << "Please enter the number:";
CIN >> Num;
listnode* head = new ListNode (0);
listnode* first = head;
for (int i = 0; i < num; i++) {int n;
CIN >> N;
listnode* NewNode = new ListNode (n);
Head->next = NewNode;
head = NewNode;
} return first->next;
} ListNode *mergetwolists (ListNode *l1, ListNode *l2) {listnode* H1 = L1;
listnode* H2 = L2;
listnode* ans = new ListNode (0);
listnode* L3 = ans;
while (H1&&H2) {if (H1->val <= h2->val) {ans->next = h1;
ans = H1;
H1 = h1->next;
} else{ Ans->next = h2;
ans = h2;
H2 = h2->next; }} Ans->next = h1?
H1:H2;
Return l3->next;
}
};
int main () {solution S;
listnode* L1 = s.create ();
listnode* L2 = S.create ();
listnode* L3 = s.mergetwolists (L1, L2);
while (L3) {cout << l3->val << "";
L3 = l3->next;
} cout << Endl;
return 0; }
The
Attaches the establishment of the linked list for testing.