How to merge two ordered linked lists in C language: just splice all the nodes of the two specified ordered linked lists. For example, the two ordered linked lists are [1->2->4] and [1->3->4], and the merged ordered linked list is [1->1->2- >3->4->4].
Specific method:
Merge two ordered linked lists into a new ordered linked list and return. The new linked list is formed by concatenating all the nodes of the two given linked lists.
(Video tutorial recommendation: java course)
Input:
1->2->4, 1->3->4
Output:
1->1->2->3->4->4
Analysis: The two linked lists are Ordered linked lists, so just traverse the two linked lists in sequence to compare their sizes.
Code implementation:
/** * 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; }
Graphic tutorial sharing: Getting started with java
The above is the detailed content of How to merge two ordered linked lists in C language. For more information, please follow other related articles on the PHP Chinese website!