題目:
文章來源:http://www.zghlxwxcb.cn/news/detail-848576.html
題解:文章來源地址http://www.zghlxwxcb.cn/news/detail-848576.html
/**
* 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) {
//如果List1和list2中有一個為空就直接返回另一個鏈表
if(list1 == NULL)
{
return list2;
}
if(list2 == NULL)
{
return list1;
}
//定義l1,l2指針分別指向list1和list2的頭節(jié)點
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;
}
}
if(l1)
{
newtail->next = l1;
}
if(l2)
{
newtail->next = l2;
}
//新鏈表的第一個節(jié)點是頭節(jié)點為無效數(shù)據(jù),因此返回頭節(jié)點的next
return newhead->next;
}
到了這里,關(guān)于C語言 | Leetcode C語言題解之第21題合并兩個有序鏈表的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!