您好,欢迎来到尔游网。
搜索
您的当前位置:首页【C编程】合并两个有序的单向链表

【C编程】合并两个有序的单向链表

来源:尔游网

本文提供三种方法合并两个有序(从小到大)的单向链表。合并后保持有序。

#include <stdio.h>
#include <stddef.h>

//
// List definition
//
typedef struct rListNode {
    int val;
    struct rListNode *next;
}ListNode;

//
// List print
//
void ListPrint(ListNode *l)
{
    while(l) {
        printf("%d\n", l->val);
        l = l->next;
        }
}

//
// Insert #n into a sorted list #l
//
ListNode *ListSortInsert(ListNode *l, ListNode *n)
{
    if (n == NULL)   return l;
    if (l == NULL)   return n;

    ListNode *cur = l;
    ListNode *nxt = l->next;

    if (n->val < cur->val) {
        n->next = cur;
        return n;
        }

    while (nxt != NULL && n->val > nxt->val) {
        // printf("i val=%d\n", nxt->val);
        cur = nxt;
        nxt = nxt->next;
        }

    cur->next = n;
    n->next   = nxt;

    return l;
}

//
// merge two sorted lists

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- axer.cn 版权所有 湘ICP备2023022495号-12

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务