c - 链接列表 - 全局变量与局部变量

标签 c linked-list global-variables

我有以下算法,用于反转链表。

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

void insert(LL_t** head, int value) 
{
    LL_t* new_node = (LL_t*) malloc(sizeof(LL_t)); 
    new_node->data  = value; 
    new_node->next = (*head); 
    (*head)    = new_node;
}

LL_t* head;
// Post: L contains the data in the original L, but in the reverse order.
void reverse(LL_t * L) {
    LL_t *current, *prev, *next;
    current = head;
    prev = NULL;
    while ( current != NULL )
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;  
    }   
    head = prev;
}

int main ()
{
struct node* L = NULL;
insert( &L, 42 );
insert( &L, 36 );
insert( &L, 14 );
insert( &L, 17 );
insert( &L, 48 );
insert( &L, 36 );

print(L);
printf("\n");
reverse(L);
print(L);

return 0;
}

在 reverse 函数之前和之后打印时,列表看起来是相同的。我相信我不小心使用了局部变量来修改我的列表,而我想直接修改列表(L)。输出:

36 48 17 14 36 42
36 48 17 14 36 42

如何使用全局变量直接修改链表?

最佳答案

你的代码的问题是你将指针按值传递给函数 reverse 并且指针 l 仍然指向第一个元素而不是你在退出后认为的最后一个元素reverse 函数,你需要通过引用传递指针并更改列表的头部,如下所示:

void reverse(LL_t **L) {
    LL_t *current, *prev, *next;
    current = *L;
    prev = NULL;
    while ( current != NULL )
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;  
    }
    head = prev;   
    *L = head;
}

电话应该是

reverse(&L);

进行此更改并立即调用

print(L) 并看到您得到一个反向链表。


如果你有一个像你在评论中所说的那样的固定原型(prototype),那就去吧

void reverse(LL_t *L) {
    LL_t *current, *prev, *next;
    current = L;
    prev = NULL;
    while ( current != NULL )
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;  
    }   
    head = prev;
}

调用应该是

reverse(L);

然后在打印调用时

print(head);

关于c - 链接列表 - 全局变量与局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29027161/

相关文章:

c - 单个散列在类对象宏中的作用

c - 我无法在结构数组中输入所有信息

c - 如何在一个循环中组合序列号和null?

java - 使用 LinkedList 而不是 Vector 来定制递归 zip 文件比较工具

objective-c - 合成 'global' 对象时出现 EXC_BAD_ACCESS

c++ - 枚举导致二进制更改与 Gcc 4.2.4 中的优化

c++ - 在一行代码中输入 2 个十六进制数字和一个字符串

C 基于用户输入的每行字符缩进

ios - 在 Swift 中使用条件编译定义全局变量

lua - 为什么在lua中访问局部变量比全局变量更快?