16. Reverse linked list

 Question : Define a function that inputs the head node of a linked list, reverses the linked list, and outputs the head node of the reversed linked list.

  Idea : Define three nodes, front, current, and back. Then judge whether the first node is empty, and if it is not empty, traverse and reverse from the second node, the second node points to the previous node, and assign the third node to the first node at the same time The variable of the node so that it can continue to traverse.

  Test case :
  1. Functional test (multiple nodes, one node)
  2. Special input case (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;

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324463641&siteId=291194637