帶頭結點的單鏈表反轉

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; }

 

方法二:插入法spa

主要思路:從鏈表的第二個結點開始,把遍歷到的結點插入到頭結點的後面,直到遍歷結束。
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,永遠指向反轉後鏈表的首元節點,不隨着回朔而變化。 }
相關文章
相關標籤/搜索