按照要求,下面是如何在代码中实现堆栈解决方案.
我没有发现 struct 构件front, rear, view
的用处,但我将它们完好无损地留在了 struct 中.也许我添加的全局变量stack_top
替换了其中一个或两个 struct 成员的意图?
我不喜欢全局变量,但堆栈指针(stack_top
)需要由两个函数共享,所以我们就在这里.如果全球赛太可怕了,你当然可以用不同的方式进行编码.它当然可以被添加为GT_SCQueue的成员,这是一个简单的修改,对吗?
经过测试、可运行的代码如下:https://godbolt.org/z/bfr4bfr5o
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define GT_SCQUEUE_SIZE 1000
/* Only one modification to the structure ... */
typedef struct {
char *buffer[GT_SCQUEUE_SIZE]; /* ... here. */
int front; /* unused */
int rear; /* unused */
int view; /* unused */
} GT_SCQueue;
GT_SCQueue scq = {{0}, -1, -1, 0};
int stack_top = -1;
/*---------------------------------------------------------------------------------------------
GT_SCQueue_Push()
Places the item in param string onto the stack.
*---------------------------------------------------------------------------------------------*/
int GT_SCQueue_Push(GT_SCQueue* scq, const char* string)
{
if(stack_top < GT_SCQUEUE_SIZE-1)
{
stack_top++;
}
else
{
printf("Stack Overflow items: %d Max: %d .... moving 1st item out of stack.\n", stack_top+1, GT_SCQUEUE_SIZE);
return 0;
}
/*Add new item on the right */
scq->buffer[stack_top] = strdup(string);
if(!scq->buffer[stack_top])
{
printf("GT_SCQueue_Push() memory error!\n");
return 0;
}
printf("GT_SCQueue_Push() added element [%s]. Elements on the stack: %d Available: %d\n",
string, stack_top+1, GT_SCQUEUE_SIZE-(stack_top+1) );
/* Return success */
return 1;
}
/*---------------------------------------------------------------------------------------------
GT_SCQueue_Pop()
Pops an item off the stack and into param string.
*---------------------------------------------------------------------------------------------*/
int GT_SCQueue_Pop(GT_SCQueue* scq, char *string)
{
if(stack_top < 0)
{
printf("UNDO Stack Underflow -- index: %d", stack_top);
return 0;
}
strcpy(string, scq->buffer[stack_top] );
free(scq->buffer[stack_top]);
scq->buffer[stack_top] = NULL;
printf("GT_SCQueue_Pop() popped element index: %d of string [%s]\n", stack_top, string);
stack_top--;
return 1;
}
int main()
{
char b1[20];
GT_SCQueue_Push(&scq, "Hello You!");
GT_SCQueue_Pop(&scq, b1);
printf("Report from main() -- Popped [%s]\n", b1);
}
输出:
T_SCQueue_Push() added element [Hello You!]. Elements on the stack: 1 Available: 999
GT_SCQueue_Pop() popped element index: 0 of string [Hello You!]
Report from main() -- Popped [Hello You!]