在C中使用队列反转堆栈
我需要使用队列反转堆栈。reverseStack()函数在堆栈中添加或删除整数时仅使用push()和pop(),在队列中添加或删除整数时仅使用enqueue()和dequeue() 但是我在在C中使用队列反转堆栈,c,stack,queue,reverse,C,Stack,Queue,Reverse,我需要使用队列反转堆栈。reverseStack()函数在堆栈中添加或删除整数时仅使用push()和pop(),在队列中添加或删除整数时仅使用enqueue()和dequeue() 但是我在push(&s,dequeue(&q))中遇到了一个分段错误。 谁能告诉我这是什么意思?谢谢 这是我的密码: void reverseStack(Stack *s) { Queue *q; while(!isEmptyStack(s)) //pop items from stack and
push(&s,dequeue(&q))中遇到了一个分段错误代码>。
谁能告诉我这是什么意思?谢谢
这是我的密码:
void reverseStack(Stack *s)
{
Queue *q;
while(!isEmptyStack(s)) //pop items from stack and queue into q
{
enqueue(&q, pop(s));
}
while(!isEmptyQueue(q)) //dequeue items from queue and push to stack
{
push(&s, dequeue(&q));
}
}
更新:
typedef struct _listnode{
int item;
struct _listnode *next;
} ListNode;
typedef struct _linkedlist{
int size;
ListNode *head;
ListNode *tail;
} LinkedList;
////////////////////////////////// stack ///////////////////////////////////////////////////////
typedef struct stack{
LinkedList ll;
} Stack;
//////////////////////////////////// queue ////////////////////////////////////////////////////////
typedef struct _queue{
LinkedList ll;
} Queue;
我得到了这些函数列表,我需要基于这些创建reverseStack()函数
void push(Stack *s, int item){
insertNode(&(s->ll), 0, item);
}
int pop(Stack *s){
int item;
if(!isEmptyStack(s)){
item = ((s->ll).head)->item;
removeNode(&(s->ll), 0);
return item;
}
return INT_MIN;
}
int peek(Stack *s){
return ((s->ll).head)->item;
}
int isEmptyStack(Stack *s){
if ((s->ll).size == 0)
return 1;
return 0;
}
void enqueue(Queue *q, int item){
insertNode(&(q->ll), q->ll.size, item);
}
int dequeue(Queue *q){
int item;
item = ((q->ll).head)->item;
removeNode(&(q->ll), 0);
return item;
}
int isEmptyQueue(Queue *q){
if ((q->ll).size == 0)
return 1;
return 0;
}
这里有几个问题
您的reverseStack
方法是:
void reverseStack(Stack *s)
{
Queue *q;
while(!isEmptyStack(s)) //pop items from stack and queue into q
{
enqueue(&q, pop(s));
}
while(!isEmptyQueue(q)) //dequeue items from queue and push to stack
{
push(&s, dequeue(&q));
}
}
在这里,您声明了q
,但从未定义它。你需要做的第一件事是让q
指向某个东西,或者你想写:
Queue q;
这将为处理器堆栈上的队列结构分配空间
对于编写的代码,我不理解它是如何工作的。对enqueue
的调用应该终止,因为q
从未被赋值。虽然我想这是可能的,因为C是一种友好的语言,因为你传递的是q
的地址而不是q
的值,你只是破坏了调用堆栈
在任何情况下,除非您解决了这个问题(要么将q
设置为非指针,要么通过调用malloc
为其赋值),否则您将遇到问题。如果确实应该动态分配,则在该函数中将&q
替换为q
您的push
定义为:
void push(Stack *s, int item){
insertNode(&(s->ll), 0, item);
}
这意味着您需要传递一个堆栈*
(指向堆栈的指针)作为第一个参数
但是在reverseStack
函数中,s
已经是一个堆栈*
(指向堆栈的指针)。但是您正在使用指针的地址调用push
。您正在传递一个堆栈**
(指向堆栈指针的指针)
正确的做法是:
push(s, dequeue(q)); // or maybe dequeue(&q), depending on how you
// you end up defining q.
您的C编译器应该在这些行中给出错误。或既然是C,也许它只是给了你警告
编译器警告只不过是一个伪装的错误。使用尽可能高的警告级别编译,启用“警告为错误”选项,并修复每个警告。能否发布push()的代码?使用调试器和单步加载程序。如果您不知道如何使用调试器,现在是学习的最佳时机。这会帮你节省很多时间。你好,我想我会给出我的意见。OP提供的答案已经是90%。这个概念已经是正确的了。唯一的错误就是队列的声明。只要添加这些行,问题就解决了:队列q;q、 ll.head=NULL;q、 ll.size=0;嘿,向下投票者:让我知道这个答案有什么问题,这样我就可以修正它了。