一:题目
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
}
二:题目分析
对于该题,一般又两种解法,分别是
- 使用栈结构,先将结点按顺序压栈,然后进行出栈输出。这种符合先进后出的原则。
- 一般的符合先进后出的原则,我们就可以使用递归的手法进行输出。因为函数的调用也是以栈的形式进行的。不过如果链表很长,则会引起栈溢出的现象。
三:源码
栈方式:
void PrintListReversingly_Iteratively(ListNode* pNode) {
std::stack<ListNode*> stackNode;
ListNode *pCurNode = pNode;
while (pCurNode != nullptr) {
stackNode.push(pCurNode);
pCurNode = pCurNode->m_pNext;
}
printf("Print List Reversingly: ");
while (!stackNode.empty()) {
ListNode *pStackNode = stackNode.top();
if (pStackNode != nullptr) {
printf("%d\t", pStackNode->m_nKey);
}
stackNode.pop();
}
}
递归的方式:
void PrintListReversingly_Recursively(ListNode* pNode) {
if (pNode == nullptr) {
printf("Print List Reversingly: ");
return;
}
if (pNode->m_pNext != nullptr) {
PrintListReversingly_Recursively(pNode->m_pNext);
}
else {
printf("Print List Reversingly: ");
}
printf("%d\t", pNode->m_nKey);
}
四:测试
如下为测试代码:
void TestPrintListReversingly() {
ListNode *pNode = new ListNode();
ListNode *pCurNode = pNode;
for (int i = 0; i < 5; i++) {
pCurNode->m_nKey = i;
pCurNode->m_pNext = new ListNode();
pCurNode = pCurNode->m_pNext;
}
pCurNode->m_nKey = 5;
pCurNode->m_pNext = nullptr;
EPrintListReversingly::PrintListReversingly_Iteratively(pNode);
printf("\n");
EPrintListReversingly::PrintListReversingly_Recursively(pNode);
printf("\n");
EPrintListReversingly::PrintListReversingly_Iteratively(nullptr);
printf("\n");
EPrintListReversingly::PrintListReversingly_Recursively(nullptr);
printf("\n");
}
由于是测试代码,这里没有写delete,大家在编码的过程中还是要记得释放空间。
运行结果: