关闭

有序链表(无头节点)的建立(后插法)和合并

标签: 链表合并c有序链表
194人阅读 评论(0) 收藏 举报
分类:

代码

#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
    int val;
    struct ListNode *next;
};
void printList(ListNode* ln1)
{
    struct ListNode *p, *ln;
    printf("list are as follow:---------\n");
    p = (struct ListNode*)malloc(sizeof(struct ListNode));
    p->next = ln1;
    ln = p;
    while((ln=ln->next))
    {
        printf("%d\n",ln->val);
    }
}
ListNode* after_insert(int* arr, int len)
{
    ListNode *l,*p,*r;
    l = (ListNode*)malloc(sizeof(ListNode));
    l->next = NULL;
    r=l;

    for(int i=0; i<len; i++)
    {
        p = (ListNode*)malloc(sizeof(ListNode));
        p->val=arr[i];
        p->next=NULL;
        r->next=p;
        r=p;
    }
    return l->next;
}

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
    //No header node
    struct ListNode *l, *r;
    l = (struct ListNode*)malloc(sizeof(struct ListNode));
    l->next = NULL;
    r=l;
    while(l1 && l2)
    {
        if(l1->val <= l2->val)
        {
            r->next = l1;
            r = l1;
            l1 = l1->next;
        }
        else
        {
            r->next = l2;
            r = l2;
            l2 = l2->next;
        }
    }
    r->next = l1 ? l1 : l2;
    return l->next;
}

int main()
{
    int arr1[] = {1,2,3,4,5,7,11,12};
    int arr2[] = {2,3,4,5,6,9,10};
    int num1 = 8;
    int num2 = 7;
    ListNode* l1 = after_insert(arr1, num1);
    ListNode* l2 = after_insert(arr2, num2);
    printList(l1);
    printList(l2);
    ListNode* l = mergeTwoLists(l1, l2);
    printList(l);
    return 0;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24481次
    • 积分:837
    • 等级:
    • 排名:千里之外
    • 原创:60篇
    • 转载:6篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论