gpt4 book ai didi

c - C 中的链表堆栈

转载 作者:行者123 更新时间:2023-12-01 17:34:55 25 4
gpt4 key购买 nike

我正在看《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/

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