文章目录
- 1. 题目信息
- 2. 解题
1. 题目信息
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 链表的基本操作,注意把前一个节点和下一个节点(l1,l2当前位置里的较小者)连起来
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {if(l1 == NULL)return l2;else if(l2 == NULL)return l1;else{ListNode *newHead = new ListNode(0);ListNode *curNode = newHead->next, *prev = newHead;while(l1 && l2){if(l1->val < l2->val){curNode = l1;l1 = l1->next;}else{curNode = l2;l2 = l2->next;}prev->next = curNode;prev = curNode;curNode = curNode->next;}if(l1 == NULL){prev->next = l2;}else//l2 == NULL{prev->next = l1;}return newHead->next;} }
};
class Solution { //2020.5.1
public:ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {if(!l1) return l2;if(!l2) return l1;ListNode* empty = new ListNode(0);ListNode* cur = empty;while(l1 && l2){if(l1->val <= l2->val){cur->next = l1;l1 = l1->next;}else{cur->next = l2;l2 = l2->next;}cur = cur->next;}cur->next = (l1 ? l1 : l2);return empty->next;}
};
《剑指Offer》同题:面试题25. 合并两个排序的链表
class Solution {
public:ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {if(!l1)return l2;if(!l2)return l1;ListNode* emptyHead = new ListNode(0);ListNode* cur = emptyHead;while(l1 && l2){while(l1 && l2 && l1->val <= l2->val){cur->next = l1;cur = l1;l1 = l1->next;}while(l1 && l2 && l1->val > l2->val){cur->next = l2;cur = l2;l2 = l2->next;}}if(!l1)cur->next = l2;elsecur->next = l1;return emptyHead->next;}
};