其他分享
首页 > 其他分享> > Leetcode 206.反转链表 迭代递归栈

Leetcode 206.反转链表 迭代递归栈

作者:互联网

Leetcode 206.反转链表 迭代递归栈

原题链接:https://leetcode-cn.com/problems/reverse-linked-list/

迭代法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = NULL;
        ListNode* cur = head;
        while (cur) {
            ListNode* rear = cur->next;
            cur->next = pre;
            pre = cur;
            cur = rear;
        }
        return pre;
    }
};
递归法
class Solution {
public:
    ListNode* reverse(ListNode* pre, ListNode* cur) {
        if (cur == NULL) return pre;
        ListNode* tmp = cur->next;
        cur->next = pre;
        return reverse(cur,tmp);
        //理解,递归的特性,把最后函数的pre给逐级回溯回去,就是说只返回最后一个函数返回的
    }
    listNode* reverseList(ListNode* head) {
        return reverse(NULL, head);
    }
};
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL) return head;
        stack<ListNode*>st;
        while (head != NULL) {
            st.push(head);
            head = head->next;
        }
        head = st.top();
        while (!st.empty()) {
            ListNode* pre = st.top();
            st.pop();
            pre->next = st.empty() ? NULL : st.top();
        }
        return head;
    }
};

标签:pre,head,ListNode,cur,递归,206,st,链表,Leetcode
来源: https://blog.csdn.net/weixin_60468770/article/details/122379137