gpt4 book ai didi

c++ - 使用链接列表插入 Pop 功能

转载 作者:行者123 更新时间:2023-11-28 05:28:44 25 4
gpt4 key购买 nike

我是数据结构的新手,很长一段时间后才开始使用 C++。在浏览了几张图之后,我决定创建自己的链表(实现一个简单的 pop 函数)。

这是我想出的代码:

#include <iostream>
using namespace std;


typedef struct node
{
int data;
node *next;
}node;


node *start;
int count_1 = 0;


void push(int x)
{
node *n = new node;
node *temp;
temp = n;
temp->data = x;
temp->next = start;
start = temp;
count_1++;
}

void ShowStack()
{
for (int i=0; i<count_1; i++)
{
node *temp = start;
cout<<temp->data<<endl;
temp = temp->next;
}
}



int main()
{
node *n = new node;
start = n;


n->data = 6;
n->next = NULL;
count_1++;

ShowStack();

push(7);
push(8);
push(9);
push(20);

//count_1=20;
ShowStack();
return 0;

}

这很基础,但我似乎遇到了问题;当我运行程序时,第一个输出是“6”,这是正确的,但在那之后,所有值都是 20(即使我将计数器硬设置为一些硬编码值,如 20(参见代码)。我会很感激如果有人可以解释这个实现有什么问题(除了程序非常困惑的事实)。另外,我会/应该采取什么步骤来获得正确的“弹出”功能。

最佳答案

在您的 ShowStack() 函数中,移动“node *temp = start;”在循环之外。

关于c++ - 使用链接列表插入 Pop 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40003935/

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