2个排序链表归并【21】(easy)
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* preHead = new ListNode(0); // 临时头结点
ListNode* prev = preHead; // prev指向临时头结点
while (l1 && l2) { // l1,l2不空时,比较
if (l1->val < l2->val) { // l1的节点小于l2
prev->next = l1; // prev与较小的节点连接
l1 = l1->next;
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next; // pre指向新链接的结点
}
if (l1) // l1有剩余
prev->next = l1; // l1连接到pre后
if (l2)
prev->next = l2;
return preHead->next;
}
};
int main() {
ListNode a(1);
ListNode b(4);
ListNode c(6);
ListNode d(0);
ListNode e(5);
ListNode f(7);
a.next = &b;
b.next = &c;
d.next = &e;
e.next = &f;
/**
* l1: 1 -> 4 -> 6 l2: 0 -> 5 -> 7
*
* result: 0 -> 1 -> 4 -> 5 -> 6 -> 7
*
*/
Solution solve;
ListNode* head = solve.mergeTwoLists(&a, &d);
while (head) {
cout << head->val << endl;
head = head->next;
}
return 0;
}