标签:merge two sorted lis leetcode acm 算法
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.
题目:合并两个单链表
思路:先比较两个各链表第一个节点,大的那个节点先设为合并的链表第一个节点,这样就找到了要合成的链表的节点了。
接下来就好办了,把两个链表中节点按照归并排序子过程原理添加到合成的链表中去。
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode *p1 = l1; ListNode *p2 = l2; ListNode* head = NULL; ListNode* current = NULL; while (p1&&p2) { if (head == NULL) { if (p1->val < p2->val) { head = current = p1; p1 = p1->next; current->next = NULL; } else { head = current = p2; p2 = p2->next; current->next = NULL; } } else { if (p1->val < p2->val) { current->next = p1; current = p1; p1 = p1->next; current->next = NULL; } else { current->next = p2; current = p2; p2 = p2->next; current->next = NULL; } } } if (p1) current->next = p1; if (p2) current->next = p2; return head; } };
leetcode.21------------Merge Two Sorted Lists
标签:merge two sorted lis leetcode acm 算法
原文地址:http://blog.csdn.net/chenxun_2010/article/details/43483291