用递归方法实现两个链表head1和head2各自有序,请把它们合并成一个链表仍然有序。(c/c++)

#include <iostream>

#include <string>

struct Node
{
    int data;
    Node *next;
};
Node* Merge(Node *head1,Node *head2)

{

if (head1==NULL)

return head2;

if (head2==NULL)

return head1;

Node *head=NULL;

if(head1->data<head2->data)

{

head=head1;

head->next= Merge (head1->next,head2);

}

else

{

head=head2;

head->next=Merge(head1,head2->next);

}

return head;

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
同样可以使用归并排序的思想,将两个升降序不一定的有序链表合并一个有序链表。具体实现如下: ```c++ #include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* cur = dummy; while (l1 && l2) { if (l1->val <= l2->val) { cur->next = l1; l1 = l1->next; } else { cur->next = l2; l2 = l2->next; } cur = cur->next; } cur->next = l1 ? l1 : l2; return dummy->next; } ListNode* sortList(ListNode* head) { if (!head || !head->next) return head; ListNode* slow = head; ListNode* fast = head->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } ListNode* mid = slow->next; slow->next = NULL; ListNode* left = sortList(head); ListNode* right = sortList(mid); if (left && right && left->val > right->val) { ListNode* tmp = left; left = right; right = tmp; } return mergeTwoLists(left, right); } int main() { ListNode* head = new ListNode(3); head->next = new ListNode(2); head->next->next = new ListNode(4); head->next->next->next = new ListNode(1); head->next->next->next->next = new ListNode(5); ListNode* sorted = sortList(head); while (sorted) { cout << sorted->val << " "; sorted = sorted->next; } return 0; } ``` 这段代码中,我们先使用快慢指针找到链表的中点,并将链表拆分两部分。然后归地对左右两部分进行排序,并用 `mergeTwoLists()` 函数将它们合并一个有序链表。值得注意的是,在合并有序链表的过程中,我们需要对左右两部分的头节点进行大小比较,保证合并后的链表仍然有序的。最后返回排序好的链表头。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值