合并两个有序链表-c语言

合并两个有序链表-c语言

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:
在这里插入图片描述

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]
解题代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
  struct ListNode  *p=(struct ListNode*)malloc(sizeof(struct ListNode));
  p->next=NULL;
   struct ListNode *s=p;
    while(list1&&list2){
        if(list1->val<=list2->val){
            p->next=list1;
             list1=list1->next;
            p=p->next;
           
        }
        else{
              p->next=list2;
            p=p->next;
            list2=list2->next;
        }

    }
    if(list1){
        p->next=list1;
    }
    if(list2){
         p->next=list2;
    }
    return s->next;


}
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是合并两个有序链表的C语言代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct ListNode { int val; struct ListNode* next; } ListNode; ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; if (l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } } ListNode* createList(int* nums, int size) { ListNode* head = NULL; ListNode** tail = &head; for (int i = 0; i < size; i++) { *tail = (ListNode*)malloc(sizeof(ListNode)); (*tail)->val = nums[i]; (*tail)->next = NULL; tail = &((*tail)->next); } return head; } void printList(ListNode* head) { while (head != NULL) { printf("%d", head->val); if (head->next != NULL) printf(" -> "); head = head->next; } printf("\n"); } int main() { int nums1[] = {1, 3, 5, 7}; int nums2[] = {2, 4, 6, 8}; ListNode* l1 = createList(nums1, sizeof(nums1) / sizeof(int)); ListNode* l2 = createList(nums2, sizeof(nums2) / sizeof(int)); ListNode* merged = mergeTwoLists(l1, l2); printList(merged); return 0; } ``` 在主函数中,我们创建了两个有序链表l1和l2,然后调用mergeTwoLists函数将它们合并成一个有序链表merged,并调用printList函数打印输出结果。在createList函数中,我们使用双重指针tail来不断更新链表尾部,并返回链表头部。在mergeTwoLists函数中,我们使用递归方式将两个有序链表合并成一个有序链表。如果其中一个链表为空,我们直接返回另一个链表;否则,我们比较两个链表头部节点的值,将较小的节点作为合并链表的头部,然后递归地将剩余的节点合并到该链表中。最后,我们返回合并后的链表头部。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值