合并单链表
2018-12-04 本文已影响9人
飞白非白
- 合并两个有序链表非递归实现
/**
* Definition for singly-linked list.
* struct ListNode
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* header = new ListNode(-1);
ListNode* cur = header;
while(l1 || l2)
{
int n = 0;
if(l1 == NULL || (l1 && l2 && l1->val > l2->val))
{
n = l2->val;
l2 = l2->next;
}
else if(l2 == NULL || (l1 && l2 && l1->val <= l2->val))
{
n = l1->val;
l1 = l1->next;
}
cur->next = new ListNode(n);
cur = cur->next;
}
ListNode *ans = header->next;
delete header;
return ans;
}
};
- 合并两个有序链表递归实现
Node* MergeListR(Node* Head1,Node* Head2)
{
if(NULL == Head1 || NULL == Head2){
if(NULL == Head1)
return Head2;
return Head1;
}
Node* newHead = NULL;
//较小的作为新链表的头
if(Head1->_data < Head2->_data){
newHead = Head1;
newHead->_next = MergeList(newHead->_next,Head2);
}else{
newHead = Head2;
newHead->_next = MergeList(Head1,newHead->_next);
}
return newHead;
}