21. Merge Two Sorted Lists

来源:互联网 发布:百度网盘搜索源码 编辑:程序博客网 时间:2024/06/05 20:06

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {struct ListNode* p1 = l1;struct ListNode* p2 = l2;struct ListNode* list = (struct ListNode*)malloc(sizeof(struct ListNode));list->next = NULL;if (!p1) return p2;if (!p2) return p1;struct ListNode* ptr = list;while (p1 && p2){if (p1->val <= p2->val){ptr->next = p1;p1 = p1->next;ptr = ptr->next;}else{ptr->next = p2;p2 = p2->next;ptr = ptr->next;}}while (p1){ptr->next = p1;p1 = p1->next;ptr = ptr->next;}while (p2){ptr->next = p2;p2 = p2->next;ptr = ptr->next;}ptr->next = NULL;return list->next;}


0 0
原创粉丝点击