递归算法反转单向链表并打印节点数据

广西大学2024年计算机考研算法题。

算法虽然不复杂,但是在考试中手搓这么多代码还是不容易的,如果是上机考试就简单了。


#include <iostream>
#include <stdio.h>
#include <memory.h>

// 节点类型定义

typedef struct tagNode {
    int data;
    struct tagNode* next;
}Node;

// 添加新节点。如果头结点不存在则创建

// 输入:1. 头结点指针;2. 新节点数据;

// 返回:头节点指针

Node* AddNode(Node* pHead, int data)
{
    if (!pHead) {
        Node* pNode = new Node();
        pNode->data = data;
        pNode->next = nullptr;
        return pNode;
    }

    Node* pCur = pHead;
    while (pCur->next) {
        pCur = pCur->next;
    }
    Node* pNode = new Node();
    pNode->data = data;
    pNode->next = nullptr;
    pCur->next = pNode;

    return pHead;
}

// 按链表顺序依次打印所有节点数据

void TraceList(Node* pHead)
{
    while (pHead) {
        std::cout << pHead->data << "-->";
        pHead = pHead->next;
    }
    std::cout << "null" << std::endl;
}

// 反转单向链表,并反向打印数据。这是题目的核心算法

void RevertAndPrint(Node* pHead, Node* pCur, Node** pNewHead)
{
    if (pCur->next == nullptr) {  // 递归到底了,将未节点保存为新的头节点
        std::cout << pCur->data << "-->";
        *pNewHead = pCur;
    }
    else {  // 中间节点。后一节点指向当前节点
        RevertAndPrint(pHead, pCur->next, pNewHead);
        pCur->next->next = pCur;
        std::cout << pCur->data << "-->";
    }

    if (pCur == pHead) {  // 回溯到头了,节点指向 null 。 这里容易忘记,导致产生链表环
        pCur->next = nullptr;
        std::cout << "null" << std::endl;
    }
}

int main()
{

    // 构建链表
    Node* pHead = nullptr;
    pHead = AddNode(pHead, 1);
    AddNode(pHead, 2);
    AddNode(pHead, 3);
    AddNode(pHead, 4);
    AddNode(pHead, 5);

   

    // 打印链表

    TraceList(pHead);

   

    // 反转链表并打印

    Node* pNewHead;
    RevertAndPrint(pHead, pHead, &pNewHead);

   

    // 打印链表

    TraceList(pNewHead);

    getchar();
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值