剑指offer 24:反转链表

在这里插入图片描述
方法一:
定义pre节点和cur节点,记得将cur节点的next暂存,迭代的将节点一个一个反转。

class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        if(!head || !head->next) return head;
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while (cur) {
    
    
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

方法二:
使用递归进行链表反转

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

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/114293074