题目:
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.
题目大意:
给定两个有序的链表,求有序合并后的链表。
思路:
链表有序合并也是数据结构里边的经典题目了。大体思路就是分别扫描两个链表,比较两个节点的大小值,把较小的节点值尾插到结果链表屁股后边,然后再次扫描两个链表,直到其中某一个链表或者两条链表同时结束。如果是某条链表提前结束则应将另一条链表的其余节点都接到结果链表上。
代码:
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *l3; //最终的链表头 if (!l1) { return l2; } else if (!l2) { return l1; } ListNode *pTemp1 = l1; ListNode *pTemp2 = l2; ListNode *pTemp3; //指向结果链表的最后一个节点 //头节点特殊处理 if (pTemp1->val < pTemp2->val) { l3 = pTemp1; pTemp3 = l3; pTemp1 = pTemp1->next; } else if (pTemp1->val > pTemp2->val) { l3 = pTemp2; pTemp3 = l3; pTemp2 = pTemp2->next; } else { l3 = pTemp1; pTemp1 = pTemp1->next; pTemp3 = l3; pTemp3->next = pTemp2; pTemp3 = pTemp2; pTemp2 = pTemp2->next; } //一个一个节点进行扫描 while (pTemp1 && pTemp2) { if (pTemp1->val < pTemp2->val) { pTemp3->next = pTemp1; pTemp3 = pTemp1; pTemp1 = pTemp1->next; } else if (pTemp1->val > pTemp2->val) { pTemp3->next = pTemp2; pTemp3 = pTemp2; pTemp2 = pTemp2->next; } else { pTemp3->next = pTemp1; pTemp3 = pTemp1; pTemp1 = pTemp1->next; pTemp3->next = pTemp2; pTemp3 = pTemp2; pTemp2 = pTemp2->next; } } //剩余节点 if (pTemp1) { pTemp3->next = pTemp1; }else if (pTemp2) { pTemp3->next = pTemp2; } return l3; } };
上述代码冗余太多。。。懒得改了=、=还是看一个比较简洁的递归版吧。
递归版:
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) { return l2; } if (l2 == NULL) { return l1; } if (l1->val <= l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } } };
时间: 2024-12-17 16:04:56