题目描述
知识点
链表
结果
实现
码前思考
- 就是很传统的链表操作
代码实现
//类似于归并排序的思想
/**
* 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) {
//设置一个虚拟结点
ListNode* dummyHead = new ListNode(0);
ListNode* endNode = dummyHead;
int val;
while(l1 != NULL && l2 != NULL){
if(l1->val >= l2->val){
val = l2->val;
l2 = l2->next;
}else{
val = l1->val;
l1 = l1->next;
}
ListNode* newNode = new ListNode(val);
endNode->next = newNode;
endNode = newNode;
}
if(l1 != NULL){
endNode->next = l1;
}
if(l2 != NULL){
endNode->next = l2;
}
return dummyHead->next;
}
};
码后反思
- 其实并不用构造新的结构体也能进行解题,只要维系一个指针
prev
就好了; - 既然只需要维系一个
prev
指针,那么还可以继续把我迭代(也就是使用循环)的代码变成使用递归来求解!
参考文档
二刷代码
与一刷的代码一样,借鉴了归并排序的思想:
//merge就是归并的意思
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dummyNode = new ListNode(0);
ListNode* ptr = dummyNode;
while(l1!=NULL && l2!=NULL){
if(l1->val < l2->val){
//printf("l1:%d\n",l1->val);
ptr->next = l1;
ptr=l1;
l1=l1->next;
}else{
//printf("l2:%d\n",l2->val);
ptr->next = l2;
ptr=l2;
l2=l2->next;
}
}
if(l1!=NULL){
//printf("l1:%d\n",l1->val);
ptr->next = l1;
}
if(l2!=NULL){
ptr->next = l2;
}
return dummyNode->next;
}
};
三刷代码
使用递归来做:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
//当涉及到链表操作的时候,都要设计一个dummyNode,这样会好操作一些
ListNode* dummyNode = new ListNode();
merge(dummyNode, list1, list2);
return dummyNode->next;
}
void merge(ListNode* head, ListNode* first, ListNode* second){
if(first == nullptr){
head->next = second;
return;
}else if(second == nullptr){
head->next = first;
return;
}else{
//两者都不为空,进行合并
if(first->val < second->val){
head->next = first;
head = first;
first = first->next;
}else{
head->next = second;
head = second;
second = second->next;
}
merge(head, first, second);
}
return;
}
};