广西大学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;
}