206. 反转链表(递归)

题目描述

leetcode - 206:https://leetcode-cn.com/problems/reverse-linked-list/

解题关键

  • 链表
  • 递归

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {

public:
    ListNode* ans;
    void dfs(ListNode* pre,ListNode* net){
        if(net==NULL){
            ans = pre;
            return;
        }
        dfs(net,net->next);
        net->next=pre;
    }

    ListNode* reverseList(ListNode* head) {
        if(head == NULL) return ans;
        dfs(head,head->next);
        head->next=NULL;
        return ans;
    }
};
posted @ 2020-06-16 18:59  _Sleeping  阅读(125)  评论(0)    收藏  举报