LeetCode 剑指 Offer 24. 反转链表 206. 反转链表(迭代、递归)

剑指 Offer 24. 反转链表

  • 链表节点的头插
/**
 * 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) {
    
    
        ListNode *newHead = nullptr,*nxt;
        while(head){
    
    
            nxt = head->next;
            head->next = newHead;
            newHead = head;
            head = nxt;
        }
        return newHead;
    }
};
  • 递归
/**
 * 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 || !head->next) return head;
        ListNode* res = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44846324/article/details/108818425