16. 反转链表

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

  思路:定义三个结点,前,当前,后。然后从判断第一个结点是否为空,不为空的话从第二个结点开始遍历反转,第二个结点指向前一个结点,同时将第三个结点赋给第一个结点的变量,好让它继续遍历。

  测试用例
  1.功能测试(多个结点、一个结点)
  2.特殊输入用例(NULL)

#include<cstdio>
#include<iostream>
using namespace std;

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

//创建结点
ListNode* CreateListNode(int value)
{
    ListNode* pNode = new ListNode();
    pNode->m_nValue = value;
    pNode->m_pNext = NULL;

    return pNode;
}

//连接结点
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
    if (pCurrent == NULL)
    {
        cout << "连接错误" << endl;
        return;
    }

    pCurrent->m_pNext = pNext;

}

//打印链表
void PrintList(ListNode* pHead)
{
    ListNode* pNode = pHead;
    while (pNode != NULL)
    {
        cout << pNode->m_nValue << " ";
        pNode = pNode->m_pNext;
    }

    cout << endl;
}

//销毁链表
void DestroyList(ListNode* pHead)
{
    ListNode* pNode = pHead;
    while (pNode != NULL)
    {
        pHead = pHead->m_pNext;
        delete pNode;
        pNode = pHead;;
    }
}

ListNode* ReverseList(ListNode* pHead)
{
    //定义三个结点
    ListNode* pReversedHead = NULL;
    ListNode* pNode = pHead;
    ListNode* pPrev = NULL;
    while (pNode != NULL)
    {
        ListNode* pNext = pNode->m_pNext;

        if (pNext == NULL)   //如果为NULL,则表示到了最后一个结点
        {
            pReversedHead = pNode;
        }

        pNode->m_pNext = pPrev;  //把指针的后一个结点往前指

        pPrev = pNode;  //把当前指针当作前一个指针,用于下一次循环被指
        pNode = pNext;  //把后一个指针保存起来
    }

    return pReversedHead;
}

void Test1()
{
    ListNode* node1 = CreateListNode(1);
    ListNode* node2 = CreateListNode(2);
    ListNode* node3 = CreateListNode(3);
    ListNode* node4 = CreateListNode(4);
    ListNode* node5 = CreateListNode(5);

    ConnectListNodes(node1, node2);
    ConnectListNodes(node2, node3);
    ConnectListNodes(node3, node4);
    ConnectListNodes(node4, node5);

    PrintList(node1);

    ListNode* pHead = ReverseList(node1);
    PrintList(pHead);

    DestroyList(pHead);

}

void Test2()
{
    ListNode* node1 = CreateListNode(1);

    PrintList(node1);

    ListNode* pHead = ReverseList(node1);
    PrintList(pHead);

    DestroyList(pHead);
}

void Test3()
{

    ListNode* pHead = ReverseList(NULL);

    DestroyList(pHead);


}

int main()
{

    Test1();
    Test2();
    Test3();

    return 0;

}

猜你喜欢

转载自my.oschina.net/134596/blog/1795790