c語言合并兩個有序鏈表的方法:拼接指定的兩個有序鏈表的所有節(jié)點即可。例如兩個有序鏈表分別為【1->2->4】和【1->3->4】,合并后的有序鏈表為【1->1->2->3->4->4】。
具體方法:
將兩個有序鏈表合并為一個新的有序鏈表并返回。新鏈表是通過拼接給定的兩個鏈表的所有節(jié)點組成的。
(視頻教程推薦:java課程)
輸入:
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; } if(l2==null){ return l1; } struct listnode *l = (struct listnode*)malloc(sizeof(struct listnode)); l->next = null; struct listnode *list1 = l1; struct listnode *list2 = l2; if(l1->val<l2->val){ l->val=l1->val; if(list1->next==null){ l->next=list2; return l; } list1=list1->next; }else{ l->val=l2->val; if(list2->next==null){ l->next=list1; return l; } list2=list2->next; } struct listnode *list = l; while(list1->next!=null&&list2->next!=null){ if(list1->val<=list2->val){ struct listnode *body = (struct listnode *)malloc(sizeof(struct listnode)); body->val = list1->val; body->next = null; list->next = body; list = list->next; list1 = list1->next; }else{ struct listnode *body = (struct listnode*)malloc(sizeof(struct listnode)); body->val=list2->val; body->next=null; list->next=body; list=list->next; list2=list2->next; } } if(list1->next==null){ while(list2->next!=null){ if(list1->val<=list2->val){ list->next = list1; list = list->next; list->next=list2; return l; }else{ struct listnode *body = (struct listnode*)malloc(sizeof(struct listnode)); body->val=list2->val; body->next=null; list->next=body; list=list->next; list2=list2->next; } } }else{ while(list1->next!=null){ if(list2->val<=list1->val){ list->next=list2; list=list->next; list->next=list1; return l; }else{ struct listnode *body = (struct listnode*)malloc(sizeof(struct listnode)); body->val=list1->val; body->next=null; list->next=body; list=list->next; list1=list1->next; } } } if(list1->next==null&&list2->next==null){ if(list1->val<=list2->val){ list->next = list1; list=list->next; list->next=list2; }else{ list->next=list2; list=list->next; list->next=list1; } } return l;}圖文教程分享:java入門