【发布时间】:2021-06-08 01:51:07
【问题描述】:
我和当前大学学生的任务是使用以下结构创建堆栈
typedef char stackitem;
struct stack {
stackitem d;
struct stack *next;
};
typedef struct stack ELEMENT;
typedef ELEMENT *POINTER;
我在打印堆栈时遇到问题。我想做的是创建一个临时堆栈,在其中打印元素,然后将其弹出。但是它似乎正在从我不想要的原始堆栈中删除它。
代码如下:
void print_stack(POINTER Top)
/*Print the contents of the stack. Do not modify the stack in any way. */
{
POINTER temp = Top;
printf("Start printing the stack ...\n");
while (temp != NULL){
printf("%c\n",temp->d);
pop(&temp);
}
}
void pop(POINTER *Top)
/* Remove the top item */
{
POINTER Top1 = *Top;
if (Top != NULL)
{
*Top = Top1->next;
// printf("Remove element %c\n", Top1->d);
free(Top1);
}
else
printf("Empty stack.\n");
}
在我看来,我正在打印并从临时指针弹出,这不应该影响原始指针顶部,但是当我插入堆栈并在第一次正确打印时打印它,然后第二次它什么也不打印。
这是我的主线
POINTER top;
top= (POINTER) NULL;
stackitem A='A';
stackitem B='B';
push(&top,A);
push(&top,B);
print_stack(top); // prints B A
print_stack(top); // prints nothing
对出了什么问题有帮助吗?
【问题讨论】: