递归方式反转链表

编辑:谯胜平      分类:程序与算法      标签:反转链表      发布时间:2021-04-13      浏览次数:697

#include<stdio.h>
#include<iostream>
using namespace std;

struct LinkNode{
    int data;
    LinkNode *next;
};

LinkNode *reverse(LinkNode *root){
    if(root == nullptr || root -> next == nullptr){
        return root;
    }
    LinkNode *head = reverse(root -> next);
    root -> next -> next = root; 
    root -> next = nullptr;
    return head; 
}

int main(){
    int n = 5, num[5] = {1,2,3,4,5};
    LinkNode *root = new LinkNode, *now = nullptr;
    now = root;
    for(int i = 0; i < n; i++){
        LinkNode *tempNode = new LinkNode;
        tempNode -> data = num[i];
        now -> next = tempNode;
        now = tempNode;
    }
    now -> next = nullptr;
    
    root = reverse(root -> next);
    now = root;
    for(int i = 0; i < n; i++){
        cout << now -> data << " ";
        now = now -> next;
    }
    return 0;
}
 


看不清?换一个