struct Node { int data; Node *next; };
方法一:就地逆序
主要思路:在遍歷鏈表的時候,修改當前結點的指針域的指向,讓其指向前驅結點。
為此,需要用三個指針變量分別指向當前結點、前驅結點、后繼結點。遍歷完所有的結點后,即可以完成指針的逆序。最后,讓頭節點的指針域指向原來最后一個元素結點。
void reverse(Node* head) {
if (head == NULL||head->next == NULL) return;
Node* pre = NULL; Node* cur = head->next; Node* next;
while (cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } head->next = pre; }
方法二:插入法
主要思路:從鏈表的第二個結點開始,把遍歷到的結點插入到頭結點的后面,直到遍歷結束。
void reverse(Node* head) { if (head == NULL||head->next == NULL) return; Node *cur, *next; cur = head->next->next;//cur初始指向第二個結點(不包括頭結點) head->next->next = NULL; while (cur) { next = cur->next; cur->next = head->next; head->next = cur; cur = next; } }
方法三:原地遞歸反轉
主要思路:我們使用遞歸的原理是每次調用函數讓他的頭指針向后走,直到走到尾節點,我們將尾節點作為頭,然后遞歸回去相當於我們倒着訪問了這個單鏈表
Node* reverse(Node* head){ //返回反轉鏈表的首元結點的地址 if (head == NULL || head->next == NULL) return head;
Node* newhead = reverse(head->next); // 先反轉后面的鏈表 head->next->next = head;//再將當前節點(head)設置為其然來后面節點(head->next)的后續節點 head->next = NULL; return newhead; // 此處返回的newhead,永遠指向反轉后鏈表的首元節點,不隨着回朔而變化。 }
