我有以下算法,旨在反转链表。
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;
}
在反向功能之前和之后打印时,列表显示为相同。我相信我不小心使用了局部变量来修改我的列表,而我想直接修改列表(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)
,看到你得到一个反向的链接列表。
如果你有一个固定的原型,就像你在评论中所说的那样,那就去吧
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);
head = L;//you don't assign to head.
reverse(L);//unused L at reverse.
print(head);