LeetCode:反转链表


C++示例:

/**
 * 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 == NULL) {
            cout << "The list is empty." << endl;
            return NULL;
        }   
        if (head->next == NULL) {
            return head;
        }
        ListNode* newHead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return newHead;
    }
    
    // 迭代实现反转
    /*ListNode* reverseList(ListNode* head) {
        if (head == NULL) {
            cout << "The list is empty." << endl;
            return NULL;
        }   
        if (head->next == NULL) {
            return head;
        }
        ListNode* p = head;
        ListNode* pPrev = NULL;
        while (p != NULL) {
            ListNode* temp = p->next;
            p->next = pPrev;
            pPrev = p;
            p = temp;            
        } 
        return pPrev;
    }*/
};

猜你喜欢

转载自www.cnblogs.com/yiluyisha/p/9266093.html
今日推荐