参见获取节点的最小值,例外情况

see get min value of nodes, exceptional case

问题已被删除,因为它包含私人代码

这是经典的合并排序代码,其中有四种情况,前提是两个列表都没有用完:

  1. a累了;
  2. b累了;
  3. a < b
  4. ab.

您已尝试通过比较合并其中一个节点为空的前两种情况,但由于您的列表可以具有 INT_MAX 作为值,因此该解决方案并不可靠。

明确写出这些案例。首先是一个小的辅助函数,它推进一个节点和 returns 值:

static int advance(Node *nd)
{
    int res = (*nd)->x;

    *nd = (*nd)->next;

    return res;
}

现在你的实际功能非常简单:

int getMin(Node *list1, Node *list2)
{
    assert(*list1 || *list2);

    if (*list1 == NULL) return advance(list2);
    if (*list2 == NULL) return advance(list1);
    if ((*list1)->x < (*list2)->x) return advance(list1);

    return advance(list2);
}

查看实际效果 on ideone