思路:
首先考虑链表1,链表2为空的情况
然后创建一个哑结点(不包含任何内容的),比较两个链表中当前指针所指向的的数字大小,将指针进行相应的移动
最后,考虑有剩余结点的可能,返回头结点的下一个(头结点为哑结点,无用 )
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;//创建一个ListNode类型的别名为ListNode
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
if(list1 == NULL)
{
return list2;
}
if(list2 == NULL)
{
return list1;
}
ListNode *L1, *L2;
ListNode *newhead, *newtail;//创建了一个哑结点
newhead = newtail = (ListNode*)malloc(sizeof(ListNode));
L1 = list1, L2 = list2;
while(L1 && L2)
{
if(L1->val <= L2->val)
{
newtail->next = L1;
newtail = newtail->next;
L1 = L1->next;
}
else
{
newtail->next = L2;
newtail = newtail->next;
L2 = L2->next;
}
}
//此时L1、L2中还可能存在剩余的结点
if(L1)
{
newtail->next = L1;
}
if(L2)
{
newtail->next = L2;
}
//新链表的第一个结点为哑结点,不包含任何信息,为无效数据
return newhead->next;
}
今日刷题小结:
认识到自己的代码能力有待提高,所以想着每天刷一道题来巩固提升一下,写代码的过程就是从宏观-微观-宏观,不断修改调整,加油!!!