剑指offer JZ-15

题目描述

输入一个链表,反转链表后,输出新链表的表头。
示例1

输入

复制
{1,2,3}

返回值

复制
{3,2,1}

思路

递归,用tail指针记录反转后链表的头部,在回溯时更改原链表。

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==nullptr) return NULL;
        if(pHead->next==NULL) return pHead;
        ListNode* tail = ReverseList(pHead->next);
        pHead->next->next = pHead;
        pHead->next = NULL;
        return tail;
    }
};
View Code
原文地址:https://www.cnblogs.com/alan-W/p/14238151.html