题目描述
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
题目大意
对两个排好序的链表进行合并。
思路分析
分别遍历,把较小的结点加入到链表中。
关键代码
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *p = l1, *q = l2;
ListNode *lm = new ListNode(-1);
ListNode *pm = lm;
while (p != NULL && q != NULL) {
if (p->val >= q->val) {
pm->next = new ListNode(q->val);
pm = pm->next;
q = q->next;
} else {
pm->next = new ListNode(p->val);
pm = pm->next;
p = p->next;
}
}
while (p != NULL) {
pm->next = new ListNode(p->val);
pm = pm->next;
p = p->next;
}
while (q != NULL) {
pm->next = new ListNode(q->val);
pm = pm->next;
q = q->next;
}
return lm->next;
}
总结
嗯,这次复习了链表。