21. 合并两个有序链表
题目链接:21. 合并两个有序链表
题目描述:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
//处理链表为空的情况
if(list1 == NULL)
{
return list2;
}
if(list2 == NULL)
{
return list1;
}
//创建新链表
ListNode* newHead = NULL;
ListNode* newTail = NULL;
//创建两个遍历指针
ListNode* l1 = list1;
ListNode* l2 = list2;
while(l1 && l2)
{
//l1小
if(l1->val < l2->val)
{
//新链表为空
if(newHead == NULL)
{
newHead = newTail = l1;
}
else //新链表不为空
{
newTail->next = l1;
newTail = newTail->next;
}
l1 = l1->next;
}
//l2小或相等
else
{
//新链表为空
if(newHead == NULL)
{
newHead = newTail = l2;
}
else //新链表不为空
{
newTail->next = l2;
newTail = newTail->next;
}
l2 = l2->next;
}
}
//l1不为空
if(l1)
{
newTail->next = l1;
}
//l2不为空
if(l2)
{
newTail->next = l2;
}
return newHead;
}
以上代码中在插入 l1 和 l2 的时候分链表为空和不为空的代码十分冗余,可以先通过malloc 为链表分配一个哨兵位就可以解决这个问题,最后再将哨兵位给释放掉即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
//处理链表为空的情况
if(list1 == NULL)
{
return list2;
}
if(list2 == NULL)
{
return list1;
}
//创建新链表
ListNode* newHead = NULL;
ListNode* newTail = NULL;
newHead = newTail = (ListNode*)malloc(sizeof(ListNode));
//创建两个遍历指针
ListNode* l1 = list1;
ListNode* l2 = list2;
while(l1 && l2)
{
//l1小
if(l1->val < l2->val)
{
newTail->next = l1;
newTail = newTail->next;
l1 = l1->next;
}
//l2小或相等
else
{
newTail->next = l2;
newTail = newTail->next;
l2 = l2->next;
}
}
//l1不为空
if(l1)
{
newTail->next = l1;
}
//l2不为空
if(l2)
{
newTail->next = l2;
}
ListNode* ret = newHead->next;
free(newHead);
newhead = NULL;
return ret;
}
解题思路:
- 创建新链表
- 遍历原链表,比较大小
- 谁小尾插到新链表中