例题:合并两个有序链表为一个新的有序链表,并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
方法一:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (!l1)
return l2;
if (!l2)
return l1;
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)), *t = head;
while (l1 && l2){
if (l1->val < l2->val){
t->next = l1;
l1 = l1->next;
}
else{
t->next = l2;
l2 = l2->next;
}
t = t->next;
}
if (l1) t->next = l1;
else if (l2) t->next = l2;
return head->next;
}
上面程序中的第14行
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)), *t = head;
可以这样理解:
struct ListNode* head;
struct ListNode* t;
head = (struct ListNode*)malloc(sizeof(struct ListNode)); //通过malloc申请这样一个结构
t = head;
方法二:递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (!l1)
return l2;
if (!l2)
return l1;
if (l1->val < l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;