解释堆栈如何在 C 中工作堆栈、如何在、工作

由网友(变坏了的好人)分享简介:我只是想简单解释一下将数据推送到堆栈时的链接过程.我知道如何使用我书中的代码进行构建,但我不确定我是否理解当您将堆栈头链接从一个移动到下一个时该过程是如何工作的.I am just wanting a simple explanation of the linking process when pushing dat...

我只是想简单解释一下将数据推送到堆栈时的链接过程.我知道如何使用我书中的代码进行构建,但我不确定我是否理解当您将堆栈头链接从一个移动到下一个时该过程是如何工作的.

I am just wanting a simple explanation of the linking process when pushing data onto a stack. I know how to build on using the code from my book, but I am not really sure I understand how the process works when you move the stack head link from one to the next.

对于像这样的堆栈:

typedef struct node
{
    void dataptr;
    struct node* link;
}STRUCT_NODE;

typedef struct
{
    int count;
    STACK_NODE* top;
}STACK;

如何更改链接以指向推送到堆栈上的新数据.我也不知道

How do you change the link to point to the new data pushed on the stack. Also I do not know

推荐答案

堆栈可以通过多种方式实现,但考虑到您表达问题的方式,我假设您的堆栈只是一个链表,类似于

Stacks can be implemented in various ways, but given the way you phrase your question I'm assuming your stack is just a linked list, something like

head
↓
A → B → C → D → 0

当您将堆栈头链接从一个移动到下一个时"图片会变为:

"when you move the stack head link from one to the next" the picture just changes to:

    head
    ↓
A → B → C → D → 0

当然 A 在此图中不再可访问,因此您最好在某个地方有另一个指向它的指针(只是为了处理它),但这是如何弹出堆栈的要点(通过使head = head->next 如果堆栈中的每个节点都是 struct nodenext 字段是 struct node*,当然 head 也是一个 struct node*).

Of course A is not reachable any more in this graph, so you'd better have another pointer to it somewhere (be it only to dispose of it), but this is the gist how how the stack is popped (by making head = head->next if each node in the stack is a struct node with a next field that's a struct node*, and of course head is a struct node* as well).

这是为了从堆栈中弹出一些东西(在这种情况下,您应该释放 A 使用的内存).详细步骤如下:

That's for popping something off the stack (and you should free the memory used by A in that case). In detailed steps, it would be:

1/保存旧头.

      head
      ↓
old → A → B → C → D → 0

2/调整头部.

          head
          ↓
old → A → B → C → D → 0

3/返回旧头(由old指向).

3/ Returning the old head (pointed at by old).

如果您是在谈论将某些东西推到堆栈上,那么这是一个涉及以下操作的操作:

If instead you're talking about pushing something onto the stack, that's an operation that involves:

1/创建一个新元素.

    head
    ↓
Z   A → B → C → D → 0

2/指向当前头部

    head
    ↓
Z → A → B → C → D → 0

3/调整头部指向它.

head
↓
Z → A → B → C → D → 0
阅读全文

相关推荐

最新文章