[LeetCode]206. 反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路:

这是一道简单难度的题。

迭代和递归的思路都一样,只要把当前节点的next域指向下下个节点,然后把当前节点的下个节点插入到链表的头部就可以了。

AC代码:

//迭代法
/**
 * 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 == nullptr)
            return nullptr;
        ListNode* cursor = head;
        while(cursor != nullptr && cursor->next != nullptr)
        {
            ListNode* temp = cursor->next;
            cursor->next = temp->next;
            temp->next = head;
            head = temp;
        }
        return head;
    }
};
//递归法
/**
 * 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 == nullptr || head->next == nullptr)
            return head;
        else
        {
            ListNode* tempCursor = reverseList(head->next);
            head->next->next = head;
            head->next = nullptr;
            return tempCursor;
        }
    }
};

Published by