leetcode 反转链表

https://leetcode-cn.com/problems/reverse-linked-list/ (整体反转)

迭代法

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *prev = NULL;
        ListNode *cur = head;
        while(cur)
        {
            ListNode *next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
};

递归法

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

https://leetcode-cn.com/problems/reverse-linked-list-ii/ (部分反转)

迭代法

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (m >= n) return head;
        if (head == NULL || head->next == NULL)  return head;
        
        int t = 1;
        ListNode *m_prev = NULL;
        ListNode *m_node = NULL;
        ListNode *n_node = NULL;
        ListNode *n_next = NULL;
        
        ListNode *prev = NULL;        
        ListNode *cur = head;
        while(cur)
        {
            ListNode *next = cur->next;
            
            if (t == m)
            {
                m_prev = prev;
                m_node = cur;                                
            }            
            else if (t > m)
            {
                cur->next = prev;
                if (t == n)
                {
                    n_next = next;
                    n_node = cur;
                    break;
                }                                
            }
            
            prev = cur;
            cur = next;
            ++t;
        }
        
        if (m_prev)
        {
            m_prev->next = n_node;
        }
        m_node->next = n_next;
        
        if (m == 1)
            return n_node;
        else
            return head;
    }
};

递归法

class Solution {
public:    
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* successor = NULL;
        if (m == 1)
        {
            return reverseN(head, n, successor);
        }
        
        head->next = reverseBetween(head->next, m-1, n-1);
        return head;
    }
    
    ListNode* reverseN(ListNode* head, int n, ListNode* &successor) {
        if (n==1)
        {
            successor = head->next;
            return head;
        }
        
        ListNode* last = reverseN(head->next, n-1, successor);
        head->next->next = head;
        head->next = successor;
        
        return last;
    }    
};

 

你可能感兴趣的:(leetcode,面试算法)