我一直在尋找在斯坦福大學圖書館下面的代碼:鏈表遞歸反向
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;
/* put the first element on the end of the list */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}
我不明白的是在例如,最近的遞歸步驟,如果列表是1-2-3-4現在對於最後一個遞歸步驟,首先是1,其餘的將是2.所以,如果你設置* head_ref = rest ..這使得列表2的頭部?有人可以解釋如何在逆轉名單的頭後成爲4?
很好的解釋!非常感謝! – harihb
@chris:\t * head_ref = rest;我不明白它..請幫助我解決這個問題 – kTiwari
head_ref是對當前遞歸級別(子)列表中第一個節點的引用。 Rest指的是列表中其餘部分的第一個節點。因此,將head_ref設置爲休息會切斷舊頭。 –