將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入: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){
struct ListNode *q=l1;
struct ListNode *p=l2;
struct ListNode *l;
struct ListNode *m=(struct ListNode*) malloc (sizeof(struct ListNode));
m->next=NULL;
l=m;
if(q == NULL) return l2;
if(p == NULL) return l1;
while(q &&p){
if(q->val<p->val){
l->next=q;
l=q;
q=q->next;
}
else{
l->next=p;
l=p;
p=p->next;
}
}
if(p){
l->next=p;
}
else{
l->next=q;
}
m=m->next;
return m;
}
這個題比較簡單,有三種情況,鏈表爲空,鏈表等長,或者鏈表一長一短。
只需要比較數值大小,接着直接改變指針指向即可,代碼如是。