题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
此题根据题目的意思是选择用单链表解决,是我从学习单链表后除了练习之外第一次使用。官网给的暴力解答法(也就是迭代法)是用三个结构体指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL) return l2;//如果l1为null,那么直接返回l2
if(l2 == NULL) return l1;//如果l2为null,那么直接返回l1
//定义结构体指针变量
struct ListNode* p1 = l1;
struct ListNode* p2 = l2;
struct ListNode* head = NULL;
if(p1->val > p2->val){//确定单链表的表头
head = p2;
p2 = p2->next;
}else{
head = p1;
p1 = p1->next;
}
struct ListNode* current = head;
while(1){
if(p1 != NULL && p2 != NULL){
if(p1->val > p2->val){
current->next = p2;
current = p2;
p2 = p2->next;
}else{
current->next = p1;
current = p1;
p1 = p1->next;
}
}
if(p1 == NULL){//如果p1为null时
current->next = p2;
break;
}
if(p2 == NULL){//如果p2为null时
current->next = p1;
break;
}
}
return head;
}