C语言 反向函数内的第二个堆栈带有指针警告

voase2hg  于 2023-02-15  发布在  其他
关注(0)|答案(1)|浏览(77)

我有下面的堆栈实现使用双向链表,我想在reverse函数中使用第二个堆栈,但是我得到了错误。如何做到这一点,假设我想返回s2

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

typedef struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
} Node;

//---------------------Stack---------------------

typedef struct Stack {
    int size;
    Node* head;
    Node* tail;
    int top;
} Stack;

const Stack stack_init = { .size = 0, .head = NULL, .tail = NULL, .top = -1 };

Node* create_node(int elm) {
    Node* node = malloc(sizeof * node);
    if (!node) return node;
    node->data = elm;
    node->prev = NULL;
    node->next = NULL;
    return node;
}

int is_empty_s(Stack *s) {
    return s->tail == NULL;
}

void push(Stack *s, int elm) {
    Node* updated_head = create_node(elm);
    if (!s->head) {
        s->head = updated_head;
        s->tail = s->head;
    } else {
        updated_head->next = s->head;
        s->head->prev = updated_head;
        s->head = updated_head;
    }
    s->size++;
    s->top = s->head->data;
}

int pop(Stack *s) {
    if (!is_empty_s(s)) {
        Node* node = s->head;
        int elm = node->data;
        s->head = s->head->next;
        if (s->head) {
            s->head->prev = NULL;
            s->top = s->head->data;
        }
        else {
            s->tail = NULL;
            s->top = -1;
        }
        s->size--;
        free(node);
        return elm;
    }
}

Stack* reverse_s(Stack *s) { // iterative: using another stack, queue
    Stack *s2 = stack_init;
    while (s->tail) {
        push(s2, pop(s));
    }
    return s2;
}

int main() {

    Stack s1 = stack_init;
    // Queue queue1 = queue_init; { .size = 0, .head = NULL, .tail = NULL, .front = -1 };
    push(&s1, 5);
    push(&s1, 4);
    return 0;
}

正如你所看到的,reverse函数还没有完成,我是C新手,不知道如何处理这个语法。

fnvucqvd

fnvucqvd1#

reverse_s中,s2的类型为 pointer-to-Stackstack_init的结构类型为 Stack。将Stack值分配给Stack *变量不兼容。
reverse_s的几个选项:
返回一个Stack结构。

Stack reverse_s(Stack *s) {
    Stack s2 = stack_init;

    while (s->tail)
        push(&s2, pop(s));

    return s2;
}

返回一个 pointer-to-Stack,为结构动态分配内存。

Stack *reverse_s(Stack *s) {
    Stack *s2 = malloc(sizeof *s2);
    *s2 = stack_init;

    while (s->tail)
        push(s2, pop(s));

    return s2;
}

修改原始结构。

void reverse_s(Stack *s) {
    Stack s2 = stack_init;

    while (s->tail)
        push(&s2, pop(s));

    memcpy(s, &s2, sizeof *s);
}

相关问题