程序员代码面试指南 2.19:合并两个有序的单链表
https://www.nowcoder.com/practice/98a51a92836e4861be1803aaa9037440
1、思路
同时遍历两条有序链表,将较少的节点接到
head
之后;当一条链表遍历完毕后,直接将另一条链表剩余部分全部接在后面即可。
2、代码
list_node * merge_list(list_node * head1, list_node * head2) { list_node *head = new list_node(), *p = head; while (head1 != nullptr && head2 != nullptr) //两条链表都不为空时 { if (head1->val < head2->val) //每次选择较小的节点 { p = p->next = head1; head1 = head1->next; } else { p = p->next = head2; head2 = head2->next; } } if (head1 != nullptr) p->next = head1; //判断两条链表是否有剩余 if (head2 != nullptr) p->next = head2; return head->next; }
程序员代码面试指南(C++版题解) 文章被收录于专栏
主要是为左程云的《程序员代码面试指南》这本书改写C++版的题解。