且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在使用 calloc 后检查列表数组中的单个列表是否为空的***方法是什么?

更新时间:2021-07-13 06:32:06

同时处理两个链表虽然很繁琐而且很烦人,但这是可行的:

Working with two linked lists simultaneously is kind of fussy and annoying, but it is doable:

int move_card(Stack **source, Stack **target, int source_pos, int target_pos) {
    // Walk through the linked list, but in every case stop one short of the
    // insertion point

    // Walk through the source chain and identify which pointer needs
    // to be manipulated.
    for (int i = 0; i < source_pos; ++i) {
        if (*source == NULL) {
            return -1;
        }

        source = &((*source)->nextPtr);
    }

    // Walk through the target chain and identify the insertion point.
    for (int i = 0; i < target_pos - 1; ++i) {
        if (*target == NULL) {
            return 1;
        }

        target = &((*target)->nextPtr);
    }

    // Capture the pointer we're actually moving
    Stack* moving = *source;

    // Skip this link in the chain by reassigning source
    *source = moving->nextPtr;

    // Capture the record that's being bumped
    Stack* bumped = *target;

    // Reassign the target
    *target = moving;

    // Re-link the bumped entry back in the chain
    moving->nextPtr = bumped;

    return 0;
}

我***地重命名了一些东西,以使其更易于理解.请注意,它如何使用双指针,以便在必要时可以操纵原始指针.当从链表中删除第一张卡时,指向头"的指针被指向.条目必须更改.

Where I've taken the liberty of renaming a few things to make this easier to understand. Notice how it uses a double pointer so it can manipulate the original pointers if necessary. When removing the first card from a linked list, the pointer to the "head" entry must change.

这是更完整的演示",利用该代码:

Here's a more complete "demo" harness for that code:

#include <stdio.h>
#include <stdlib.h>

struct stack {
    char card[2];
    struct stack *nextPtr;
};
typedef struct stack Stack;

Stack* make_stack(char face, char suit, Stack* nextPtr) {
    Stack* stack = calloc(1, sizeof(Stack));
    stack->card[0] = face;
    stack->card[1] = suit;
    stack->nextPtr = nextPtr;

    return stack;
}

void print_stack(Stack* stack) {
    while (stack) {
        printf("%c%c ", stack->card[0], stack->card[1]);
        stack = stack->nextPtr;
    }

    printf("\n");
}

int main(int argc, char** argv) {
    Stack* source = make_stack('A', 'S', make_stack('2', 'S', make_stack('3', 'S', NULL)));
    Stack* target = NULL;

    print_stack(source);

    move_card(&source, &target, 2, 0);

    print_stack(source);
    print_stack(target);

    return 0;
}

使用简化卡模型的地方.

Where that uses a simplified Card model.