206. Reverse Linked List(使用递归的方法,新建一个指针,总共使用两个指针)

非递归方法参考:206. Reverse Linked List(只需新建两个指针,借用传入的head指针,共使用三个指针)

递归实现代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL) return head;
        
        ListNode* tmp=reverseList(head->next);//把head->next后面的链表翻转
        head->next->next=head;//翻转后的链表,head->next是尾节点,把head连接到尾部
        head->next=NULL;//因为head是尾部,所以指向NULL
        return tmp;
    }
};

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注