我正在尝试通过双指针反向链接,并且gcc一直给我退出状态-1:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
struct Node * link;
} Node;
Node ** reverse(Node ** rootp)
{
if ( ( rootp == NULL )|| ( (*rootp) == NULL) || (((*rootp)->link) == NULL) )
{
return rootp;
}
Node ** old_previous = (Node **)malloc(sizeof(Node));
Node ** previous = (Node **)malloc(sizeof(Node));
previous = rootp;
Node ** current = (Node **)malloc(sizeof(Node));
current = &((*rootp)->link);
((*previous)->link) = NULL;
while ( ((*current)->link) != NULL )
{
old_previous = previous;
previous = current;
current = &((*current)->link);
((*previous)->link) = (*old_previous);
}
((*current)->link) = (*previous);
free(old_previous);
free(previous);
free(current);
return current;
}
void print_list(Node * root)
{
if ( root == NULL )
{ return; }
if (root->link == NULL)
{ printf("%p\n\n",root); return; }
printf("%p ",root);
print_list(root->link);
}
int main(void)
{
Node * first = (Node *)malloc(sizeof(Node));
Node * second = (Node *)malloc(sizeof(Node));
Node * third = (Node *)malloc(sizeof(Node));
first->link = second;
second->link = NULL;
third->link = NULL;
print_list(first);
Node ** rev = reverse(&first);
print_list(*rev);
free(first);
free(second);
free(third);
return 0;
}
由于gcc仅报告退出状态-1,所以我想我必须在反向函数中的某个地方取消引用NULL节点。当我的一个朋友将反向函数的思想翻译成python程序时,它就很好了。反向函数中某处必须存在指针问题。你们中的任何人对我在做什么错有任何想法吗?
谢谢大家考虑。