我有以下短代码,这是解决链接列表反转问题的解决方案。
void backwardslist(atom** head) {
atom* first;
atom* second;
if (*head == NULL) return; //if list is empty
first = *head;
second = first->next; // intuitive
if (second == NULL) return;
backwardslist(&second); // recursive call with 2nd one as head, after we got variables
first and second
first->next->next = first; // when we get to the end, we rearrange it
first->next = NULL; // so last one is pointing to first, first is pointing to NULL
*head = second; // I dont understand this part, so the head is changing from the last,
to the second element as the recursion goes to the beginning or am i
missing something?
}
不是第二个=(指向递归中两个指针中第二个的指针)?
所以第一次,我明白,它应该指向最后一个,
但随着递归的建立,它不断变化*从头到尾。
正在使用的第二个atm是什么?
谢谢你们
答案 0 :(得分:0)
想到一个简单的答案就是递归调用你的函数直到达到目的。然后返回最后一个节点。当递归函数返回时,设置返回头节点的节点的下一个指针。
1) A->B->C->D
2) A->B->C->D->C
3) A->B->C->D->C->B
4) A->B->C->D->C->B->A
5) D->C->B->A->Null
答案 1 :(得分:0)
void recursiveReverse(struct node** head_ref)
{
struct node* first;
struct node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}