Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题意:合并两个有序单链表,合并后的仍然是有序的。。。。。。。。。。。。。。。。。。。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
//首先判断有没有空链表的情况。。。。。
if(l1 && !l2)
return l1;
if(!l1 && l2)
return l2;
if(!l1 && !l2)
return NULL;
//还是和之前的002题要保存新链表头,中间节点head负责遍历
struct ListNode* head;
struct ListNode* ret;
//找到新链表的头
if(l1->val<l2->val){
head=l1;
l1=l1->next;
}else{
head=l2;
l2=l2->next;
}
ret=head;
//负责遍历。哪个小就指向哪个,直到有一个遍历完
while(l1&&l2){
if(l1->val<l2->val){
head->next=l1;
l1=l1->next;
}else{
head->next=l2;
l2=l2->next;
}
head=head->next;
}
//遍历完后看看谁还剩下直接指向剩下的部分
if(l1){
head->next=l1;
}
if(l2){
head->next=l2;
}
return ret;
}
。。。。。。。。。。。。。。。。太笨了。。。。。。。。。。。。。。。。继续练习吧少年。。。。。。。。。。。。。。。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。