【面试系列】反转链表

题意:
原题链接

代码:
1 、 1、 1递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        if(head == NULL || head->next == NULL) return head;
        ListNode *next_tail = head->next;
        ListNode *next_head = reverseList(head->next);
        next_tail->next = head;
        head->next = NULL;
        return next_head;
    }
};

2 、 2、 2迭代

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        if(head == NULL || head->next == NULL) return head;
        
        ListNode *pre = NULL, *cur = head;
        while(cur) {
    
    
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        } 
        return pre;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43900869/article/details/119761411