gpt4 book ai didi

c - 使用链表实现堆栈。我哪里错了?

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:27 24 4
gpt4 key购买 nike

这是我用 C 编写的代码:

#include<stdio.h>
struct Node
{
int info;
struct Node *next;
};
void init_Node(struct Node *n)
{
n->next = NULL;
}
struct Node *front = NULL;
void display()
{
struct Node *rear = front;
if(rear == NULL)
printf("List is empty!\n");
else
{
printf("[%i]-->",rear->info);
rear = rear->next;
}
printf("NULL");
printf("\n");
}
void addEnd(int x)
{
struct Node *n = malloc(sizeof(struct Node));
struct Node *rear = front;
n->info = x;
if(front == NULL)
front = n;
else
{
while(rear->next != NULL)
rear = rear->next;
rear->next = n;
rear = n;
}
display();
}
void deleteEnd()
{
struct Node *rear = front;
if(front == NULL)
printf("Stack is Empty!");
else
{
while(rear->next->next != NULL)
{
rear = rear->next;
}
printf("Popped : %i\n", rear->next->info);
rear->next = NULL;
display();
}
}
int main()
{
struct Node *n = malloc(sizeof(struct Node));
init_Node(n);
clrscr();
addEnd(23);
addEnd(45);
addEnd(8);
addEnd(57);
deleteEnd();
addEnd(98);
deleteEnd();
getch();
return 0;
}

下面的输出是在 C++ 中使用类完成实现时的输出。该程序的输出应该是这样的 -

enter image description here

但是我的代码的输出是这样的—— enter image description here

编辑添加 while() 循环并添加 n->next = NULL; 之后输出结果是: enter image description here

我哪里错了?

最佳答案

你需要两个改变:

void display()
{
struct Node *rear = front;
if(rear == NULL)
printf("List is empty!\n");
else
{
// CHANGE 1: You need a while loop here
while(rear != NULL) {
printf("[%i]-->",rear->info);
rear = rear->next;
}
}
printf("NULL");
printf("\n");
}

void addEnd(int x)
{
struct Node *n = malloc(sizeof(struct Node));
struct Node *rear = front;
n->info = x;
// CHANGE 2: You need to clear n->next to NULL.
n->next = NULL;
if(front == NULL)
front = n;
else
{
while(rear->next != NULL)
rear = rear->next;
rear->next = n;
rear = n;
}
display();
}

关于c - 使用链表实现堆栈。我哪里错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27302170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com