c - C 中的链表堆栈

标签 c linked-list stack

我正在看《Programming Interviews Exposed》一书中的以下段落,其中提到了 C 中链表堆栈的实现:

typedef struct Element {
   struct Element *next;
   void *data; 
} Element;

void push( Element *stack, void *data ); 
void *pop( Element *stack );

Now consider what will happen in these routines in terms of proper functionality and error handling. Both operations change the first element of the list. The calling routine’s stack pointer must be modified to reflect this change, but any change you make to the pointer that is passed to these functions won’t be propagated back to the calling routine. You can solve this problem by having both routines take a pointer to a pointer to the stack. This way, you can change the calling routine’s pointer so that it continues to point at the first element of the list. Implementing this change results in the following:

void push( Element **stack, void *data ); 
void *pop( Element **stack);

有人可以换句话说,为什么我们需要在这里使用双指针?我对所提供的解释有点不确定。

最佳答案

它类似于 C 中著名的 swap() 函数。

案例一:

void swapFails(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
}

案例二:

void swapOk(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

然后我们像这样调用交换:

int x = 10;
int y = 20;

案例一:

swapFails(x, y);

案例二:

swapOk(&x, &y);

请记住,我们想要更改 x 和 y 的值。对于更改数据类型的值,我们需要指针。将此提升到一个新的水平以获得指导。对于更改指针的值,我们需要双指针。

对于使用链表的堆栈: 如果您压入值 10、20 和 30,它们的存储方式如下:

top --- bottom
30 -> 20 -> 10

所以你会看到每次你从栈中压入或弹出值时,这是一个链表,链表的顶部或第一个节点发生变化。因此你需要双指针。

关于c - C 中的链表堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240504/

相关文章:

c - 我可以使用函数在c中有效地实现指向字符串的指针吗?

C:最小和最大输出

c - 我如何知道对特定程序使用哪个 exec 命令?

c++ - 有没有办法将 std::stack<pointer> 转换为 std::stack<const pointer>?

c - 堆栈的链表,head->next 不断变为 null

C:关于 Beej 的网络指南的问题......这里有一个假设吗?

c - 链表实现

c - C编程中的段错误链表

c - 编写一个重新排列链表的函数,将偶数位置的节点放在列表中奇数位置的节点之后

C 堆栈分配