《剑指offer》面试题24:反转链表

更多剑指offer面试习题请点击:《剑指offer》(第二版)习题目录索引

题目:
   定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。结点定义如下:

typedef struct ListNode
{
    int m_nValue;
    struct ListNode* m_pNext;
}ListNode;

< code >

ListNode* ReverseList(ListNode* pHead)
{
    //如果链表为空或者链表只有一个节点,直接返回pHead
    if (pHead == nullptr || pHead->m_pNext == nullptr)
        return pHead;

    ListNode* prev = nullptr;
    ListNode* cur = pHead;
    ListNode* tail = cur->m_pNext;

    while (cur != nullptr)
    {
        cur->m_pNext = prev;

        prev = cur;
        cur = tail;
        if (tail != nullptr){
            tail = tail->m_pNext;
        }
    }
    return prev;
}

< Test Code>

ListNode* Test(ListNode* pHead)
{
    printf("The original list is: \n");
    PrintList(pHead);

    ListNode* pReversedHead = ReverseList(pHead);

    printf("The reversed list is: \n");
    PrintList(pReversedHead);

    return pReversedHead;
}

void Test1()
{
    ListNode* pNode1 = CreateListNode(1);
    ListNode* pNode2 = CreateListNode(2);
    ListNode* pNode3 = CreateListNode(3);
    ListNode* pNode4 = CreateListNode(4);
    ListNode* pNode5 = CreateListNode(5);

    ConnectListNodes(pNode1, pNode2);
    ConnectListNodes(pNode2, pNode3);
    ConnectListNodes(pNode3, pNode4);
    ConnectListNodes(pNode4, pNode5);

    ListNode* pReversedHead = Test(pNode1);

    DestroyList(pReversedHead);
}

// 输入的链表只有一个结点
void Test2()
{
    ListNode* pNode1 = CreateListNode(1);

    ListNode* pReversedHead = Test(pNode1);

    DestroyList(pReversedHead);
}

// 输入空链表
void Test3()
{
    Test(nullptr);
}

int main(int argc, char* argv[])
{
    Test1();
    Test2();
    Test3();

    system("pause");
    return 0;
}

如需要创建、打印链表的代码,请点击:https://blog.csdn.net/Tianzez/article/details/79965449

测试结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/tianzez/article/details/80019739