双向链表反转

链表节点定义:

struct ListHao
{
    ListHao * prev = nullptr;
    ListHao * next = nullptr;
    double element = 0;
};

ListHao* ReverseList(ListHao* first);

现要实现输入一个双向链表头指针,反转链表,并返回反转后的头指针。链表节点如下图,关键代码如下:

ListHao* ReverseList(ListHao* head)
{
    if (head == nullptr || head->next == nullptr)
    {
        return head;
    }

    //Assume that this list is not loop.
    ListHao *pNode = head, *pPre = nullptr;

    while (pNode != nullptr)
    {
        ListHao* pNext = pNode->next;
        pNode->next = pPre;
        pNode->prev = pNext;

        pPre = pNode;
        pNode = pNext;
    }
    return pPre;
}


测试代码:

void main()
{
    ListHao* list = new ListHao();
    list->element = rand() / 101;
    list->prev = nullptr;
    for (int ii = 0; ii < 5; ii++)
    {
        ListHao* temp = new ListHao();
        temp->element = rand() / 101;
        list->next = temp;
        temp->prev = list;

        list = temp;
    }

    cout << "Backward output:" << endl;
    cout << list->element << endl;
    while (list->prev != nullptr)
    {
        list = list->prev;
        cout << list->element << endl;
    }

    ListHao* result = ReverseList(list);

    cout << "Forward output after reverse:" << endl;
    cout << result->element << endl;
    while (result->next != nullptr)
    {
        result = result->next;
        cout << result->element << endl;
    }

    system("pause");
}




你可能感兴趣的:(C++)