链表-206. 反转链表

时间:2021-07-14
本文章向大家介绍链表-206. 反转链表,主要包括链表-206. 反转链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

1.题目描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表

2.思路

用二个指针,pre指向反转链表的首结点,curr指向链表的首结点,每次将curr->next指向pre
可以迭代,可以递归

3.1迭代法:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr;
        ListNode *curr = head;
        while(curr)
        {
           ListNode *p = curr;
           curr = curr->next;
           p->next = pre;
           pre = p;
        }
        return pre;
    }
};

3.2递归法

递归是逆序完成逆转,递归返回

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    if(!head || !head->next) return head;

    ListNode *p = reverseList(head->next); //p always points to the last node of the linklist, which is also the first node of the reverseList
    head->next->next = head;
    head->next = nullptr; // the last node->next of the reverseList must point to null

    return p;

    }
};

原文地址:https://www.cnblogs.com/liushz-blog/p/15010473.html