#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *link;
};
struct Node *top = NULL;
void Push(int);
void Pop();
void Print();
int main(void)
{
Push(3);
Push(6);
Print();
Push(5);
Pop;
Push(1);
Print();
return 0;
}
void Push(int i)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = i;
temp->link = top->link;
top = temp;
}
void Pop()
{
struct Node* temp;
if(top == NULL) return;
temp = top;
top = top->link;
free(temp);
}
void Print()
{
struct Node* p = top;
if(p->link != NULL)
{
printf("Stack: \n");
printf("%d\n",p->data);
p = p->link;
}
return;
}
改动处见注释,供参考:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *link;
};
struct Node *top = NULL;
void Push(int);
void Pop();
void Print();
int main(void)
{
Push(3);
Push(6);
Print();
Push(5);
Pop(); // Pop; 修改
Push(1);
Print();
return 0;
}
void Push(int i)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = i;
temp->link = top; //temp->link = top->link; 修改
top = temp;
}
void Pop()
{
struct Node* temp;
if(top == NULL) return;
temp = top;
top = top->link;
free(temp);
}
void Print()
{
struct Node* p = top;
printf("Stack:"); //修改
while (p) //if(p->link != NULL) 修改
{
printf("%d ",p->data);
p = p->link;
}
printf("\n"); //修改
return;
}
编码过程中,我们需要对自己的指针负责,往往导致bug出现或者找不到问题所在地的就是这种细节。最后,原创不易,希望能够改正文章的错误,多提意见留言,谢谢。
问题可能出在链表实现的代码上,可能是没有正确实现入栈和出栈操作,或者没有正确修改链表指针的指向导致无法输出栈中的内容。要解决这个问题,可以检查以下几个方面:
检查链表入栈和出栈的代码实现是否正确,可以手动模拟一下入栈和出栈的操作,看是否达到了预期的效果。
检查链表指针的指向是否正确,包括入栈后链表表头是否正确修改,以及出栈后链表表头是否正确修改。
检查输出栈的内容的代码是否正确,包括遍历链表时是否正确使用了指针,以及是否正确输出了栈中的每个元素。
根据不同的实现方式,上述三个方面都可能存在问题,需要仔细检查代码并进行调试。
以下是一个简单的链表实现栈的代码示例:
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int data;
struct node_s *next;
} node_t;
typedef struct stack_s {
node_t *top;
int count;
} stack_t;
void push(stack_t *s, int data) {
/* 创建一个新节点,并将节点插入链表头部 */
node_t *node = (node_t*)malloc(sizeof(node_t));
node->data = data;
node->next = s->top;
s->top = node;
s->count++;
}
int pop(stack_t *s) {
if (s->count <= 0) {
/* 栈为空,返回 -1 表示出错 */
return -1;
}
/* 从链表头部删除一个节点,并返回节点数据 */
node_t *node = s->top;
int data = node->data;
s->top = node->next;
s->count--;
free(node);
return data;
}
int main() {
stack_t s = {NULL, 0};
/* 入栈 */
push(&s, 1);
push(&s, 2);
push(&s, 3);
/* 出栈并输出 */
while (s.count > 0) {
int data = pop(&s);
printf("%d ", data);
}
return 0;
}
在此代码中,每个节点包括两个部分:数据和指向下一个节点的指针。栈包括两个部分:栈顶指针和元素个数。入栈操作使用链表头插法,出栈操作从链表头部删除一个节点并返回节点数据。