力扣-21.合并两个有序链表-代码说明超详细
● 先判断两个链表头节点存在空时的情况
● 找到两个头节点中数值较小的一个作为最终返回的头节点head
● cur1为头节点的next结点
● cur2为数据较大的头节点中的第一个节点
● pre节点初值指向head节点,(由pre来串接两个链表)
● 在两个头节点都不为空情况下,进行下面的循环:
○ pre指向cur1与cur2中较小的节点(由pre来串接两个链表)
○ 随后cur1与cur2中较小的节点后移进行更新,另一个位置不变
● 跳出循环后,cur1与cur2之中必有一个为空,pre的next指向不为空的那个节点。
java版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode head1, ListNode head2) {
//判断是否有空链表
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
// 判断最终返回的链表头节点:head1,head2哪个头节点的数值小,哪个是最终的头节点
ListNode head = head1.val <= head2.val ? head1 : head2;
// 小头节点的next为cur1
ListNode cur1 = head.next;
// 大头节点的第一个为cur2
ListNode cur2 = head == head1 ? head2 : head1;
// pre初值为head头节点,由pre来串接两个链表(pre为新链表的尾节点)
ListNode pre = head;
while(cur1 != null && cur2 != null){
// pre的next指向cur1与cur2中值较小的节点
if (cur1.val <= cur2.val){
// 新链表的尾节点进行链接
pre.next = cur1;
cur1 = cur1.next;
}else {
// 新链表的尾节点进行链接
pre.next = cur2;
cur2 = cur2.next;
}
//新链表的尾节pre后移: pre为最终合并链表的尾节点
pre = pre.next;
}
// 跳出循环后,cur1与cur2之中必有一个为空
// pre的next指向不为空的那个节点
pre.next = cur1 != null ? cur1 : cur2;
return head;
}
}
c++版
/**
* 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* head1, ListNode* head2) {
if(head1 == NULL || head2 == NULL)
{
return head1 == NULL ? head2 :head1;
}
ListNode *head = head1->val <= head2->val ? head1 :head2;
ListNode *cur1 = head->next;
ListNode *cur2 = head == head1 ? head2 :head1;
ListNode *pre = head;
while(cur1 != NULL && cur2 != NULL)
{
if(cur1->val <= cur2->val)
{
pre->next = cur1;
cur1 = cur1->next;
}
else
{
pre->next = cur2;
cur2 = cur2->next;
}
pre = pre->next;
}
pre->next = cur1 != NULL ? cur1 : cur2;
return head;
}
};