我想编写一种迭代和递归的方式来反转链表。
不幸的是,在这两种情况下,我都遇到了类似的问题:我无法将一个节点的指针更改为另一个节点,并且在某些情况下,我在迭代列表时遇到了困难。例如,这是我的递归反向函数:
node *reverse(node *initial){
node *prev = initial;
node *nextNode;
nextNode = (node *)malloc(sizeof(struct node));
nextNode = initial->next;
if(nextNode->next == NULL){
return prev;
}
else{
nextNode = reverse(nextNode);
nextNode->next = prev;
}
}
该nextNode = initial->next;
行使程序崩溃。我确信这段代码还有很多其他问题,如果它存在致命缺陷,我愿意接受建议,但我主要只是想解决这个错误,以便我可以自己调试其余部分。在迭代版本中,导致程序崩溃的一些类似行是:
startA = startA->next; // startA is a node pointer
backNode = startB; // backNode and startB are both node pointers
backNode->data = frontNode->data; //both ints
frontNode->data = temp; //again both ints
根据要求,其余代码:
main(){
node * start = buildList();
int i;
int nodeSize = sizeof(struct node);
reverse(start);
}
和构建列表:
node *buildList(){
node *head = NULL;
node *second = NULL;
node *third = NULL;
node *fourth = NULL;
node *fifth = NULL;
head = (node *)malloc(sizeof(struct node));
second = (node *)malloc(sizeof(struct node));
third = (node *)malloc(sizeof(struct node));
fourth = (node *)malloc(sizeof(struct node));
fifth = (node *)malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data =2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data =4;
fourth->next = fifth;
fifth->data = 5;
fifth->next = NULL;
return head;
}