C++ 翻转链表

#include 

using namespace std;

struct TreeNode
{
    int val;
    TreeNode* next;
    TreeNode(int x): val(x), next(nullptr)
    {
    };
};

TreeNode* reverseList(TreeNode* head)
{
    if(head == nullptr)
    {
        return nullptr;
    }
    if(head->next == nullptr)
    {
        return head;
    }

    TreeNode* pFront = nullptr;
    TreeNode* pCur = head;
    TreeNode* pBack = head->next;

    while(pCur->next)
    {
        pCur->next = pFront;
        pFront = pCur;
        pCur = pBack;
        pBack = pBack->next;
    }
    pCur->next = pFront;
    return pCur;
}

int main()
{
    TreeNode a = TreeNode(10);
    TreeNode b = TreeNode(12);
    TreeNode c = TreeNode(13);
    
    TreeNode* head = &a;
    a.next = &b;
    b.next = &c;
    
    TreeNode* ptr = reverseList(head);
    cout << ptr->val << endl;
    
    return 0;
}

你可能感兴趣的:(笔试题)