Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用指针的C++链表栈_C++_List_Pointers_Stack - Fatal编程技术网

使用指针的C++链表栈

使用指针的C++链表栈,c++,list,pointers,stack,C++,List,Pointers,Stack,因此,我有一个堆栈,其中包含它允许的典型推送和弹出函数。我很难理解它实际上是如何在代码方面工作的。我在这里看到这个帖子, 这显示了如何向下推列表,并指向最新的元素。我有一个 node* stack; 连接到结构节点的 struct node { ItemType data; node* next; }; 如何将推拉合并到节点*下一步?最难理解的是我将如何去做。我知道它最初指向null,然后如果我推一个2,4,6,它将是6,4,2,。掌握了如何使用链表中的指针来实现这一点让我陷

因此,我有一个堆栈,其中包含它允许的典型推送和弹出函数。我很难理解它实际上是如何在代码方面工作的。我在这里看到这个帖子, 这显示了如何向下推列表,并指向最新的元素。我有一个

node* stack;
连接到结构节点的

struct node
{
    ItemType data;
    node* next;
};
如何将推拉合并到节点*下一步?最难理解的是我将如何去做。我知道它最初指向null,然后如果我推一个2,4,6,它将是6,4,2,。掌握了如何使用链表中的指针来实现这一点让我陷入了一个循环。我可以不用指针,但指针就是我的动力。谢谢你的帮助,我真的很想解决这个问题。我来这里是想很快作出回应。谢谢

编辑1: 解决了-我的推起作用了

编辑2:
我现在想跳起来。这是否意味着我必须将指针指向下一个值?如何处理旧的顶部节点?删除它,因为我新建了它?

它看起来像一个C问题

函数推送可在C++中以以下方式定义

void push( node * &stack, const ItemType &item )
{
    node *tmp = new node { item. stack };
    stack = tmp;
}
在C语言中,它可以看起来像

int push( struct node * *stack, const ItemType *item )
{
    node *tmp = malloc( sizeof( struct node ) );

    if ( tmp )
    {
        tmp->data = *item;
        tmp->next = *stack;

        *stack = tmp;
    }

    return tmp != NULL;
}
void StackClass::Push( ItemType newItem ) 
// I would declare the parameter as const ItemType &newItem 
{ 
    node* temp = new node;
    temp->data = newItem;
    temp->next = stack;

    stack = temp;
}
编辑:在你编辑了你的文章之后,我也编辑了我的文章。 指针堆栈似乎是StackClass类的数据成员。在这种情况下,成员函数可以如下所示

int push( struct node * *stack, const ItemType *item )
{
    node *tmp = malloc( sizeof( struct node ) );

    if ( tmp )
    {
        tmp->data = *item;
        tmp->next = *stack;

        *stack = tmp;
    }

    return tmp != NULL;
}
void StackClass::Push( ItemType newItem ) 
// I would declare the parameter as const ItemType &newItem 
{ 
    node* temp = new node;
    temp->data = newItem;
    temp->next = stack;

    stack = temp;
}

因此,我有一个堆栈,其中包含了它允许的典型推送和弹出功能——听起来好像你没有这样的功能。您是否研究过内存分配以及这种特殊的数据结构?你熟悉链表吗?@crashmstr对不起,我的意思是我不需要指针就能理解它。使用指针时,我很难理解指针从一端添加和删除的轨迹。因此,头部节点在推送或弹出时会发生变化。@crashmstr好的,这样我就可以在节点*next的末尾添加新元素,但如果我想弹出,我不知道如何向后移动。没有上一个节点,只有下一个节点。不要在后端添加。推送会添加一个新节点,该节点随后指向堆栈的旧头,从前面添加/删除。Hello。我的老师为我们提供了一个小框架,其中push方法是一个只有一个参数的void函数,即ItemType newItem。如果您不介意的话,我已经在上面的帖子中包含了我在编辑1中编写的代码。非常感谢。是的,这就是我想到的。我知道我一直在改变我写的东西,但我感谢你坚持我。我目前正在做我的流行音乐,但最初并没有问这个问题。我把你的答案标对了。非常感谢。