我有下面的堆栈实现使用双向链表,我想在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新手,不知道如何处理这个语法。
1条答案
按热度按时间fnvucqvd1#
在
reverse_s
中,s2
的类型为 pointer-to-Stack。stack_init
的结构类型为 Stack。将Stack
值分配给Stack *
变量不兼容。reverse_s
的几个选项:返回一个
Stack
结构。返回一个 pointer-to-Stack,为结构动态分配内存。
修改原始结构。