面试题4:从尾到头打印链表
来源:互联网 发布:新款java小轮车 编辑:程序博客网 时间:2024/05/22 04:31
方法一:利用栈实现
C++代码:
#include "stdafx.h"#include <iostream>#include <stack>using namespace std;//链表中的结点类型struct ListNode{int m_nKey;ListNode *m_pNext;};//从尾到头打印链表void PrintLinkedListReversely(ListNode *pHead){stack<ListNode *> tempStack; if (pHead != NULL){ListNode *pCurrent = pHead; ListNode *pStackNode = NULL;while (pCurrent != NULL){tempStack.push(pCurrent);pCurrent = pCurrent->m_pNext;} while (!tempStack.empty()) {pStackNode = tempStack.top();cout << pStackNode->m_nKey << " ";tempStack.pop(); }cout << endl;}}
方法二:递归实现
C++代码:
#include "stdafx.h"#include <iostream>#include <stack>using namespace std;//链表中的结点类型struct ListNode{int m_nKey;ListNode *m_pNext;};//从尾到头打印链表void PrintLinkedListReversely(ListNode *pHead){if (pHead != NULL){if (pHead->m_pNext != NULL){PrintLinkedListReversely(pHead->m_pNext);}cout << pHead->m_nKey << " ";}}int _tmain(int argc, _TCHAR* argv[]){bool isHeadNode = true;ListNode *pHeadNode = NULL;ListNode *pListNode = NULL;ListNode *pCurrentTail = NULL;while (1){if (isHeadNode){ pHeadNode = new ListNode();cin >> pHeadNode->m_nKey;pHeadNode->m_pNext = NULL;pCurrentTail = pHeadNode;isHeadNode = false;}else{pListNode = new ListNode();cin >> pListNode->m_nKey;if (pListNode->m_nKey == -1){break;}pListNode->m_pNext = NULL;pCurrentTail->m_pNext = pListNode;pCurrentTail = pListNode;}}PrintLinkedListReversely(pHeadNode);ListNode *pNode = pHeadNode;ListNode *pNext = NULL;while (pNode != NULL){pNext = pNode->m_pNext;delete pNode;pNode = pNext;} system("pause");return 0;}基于递归的代码很简洁,但它存在缺点:当链表非常长的时候就会导致函数调用的层级很深,从而有可能导致栈溢出。显然相比方法一用栈基于循环实现的代码的鲁棒性更好些。
- 面试题4:从尾到头打印链表
- 面试题5:从尾到头打印链表
- 【面试题五】从尾到头打印链表
- 面试题 -- 从尾到头 反向打印链表
- 面试题5 从尾到头打印链表
- 面试题5 从尾到头打印链表
- 面试题5:从尾到头打印链表
- 面试题5-从尾到头打印链表
- 面试题5:从尾到头打印链表
- 面试题—— 从尾到头打印链表
- 面试题五: 从尾到头打印链表
- 面试题5:从尾到头打印链表
- 《剑指Offer》面试题:从尾到头打印链表
- 面试题5:从尾到头打印链表
- 面试题6:从尾到头打印链表(offer)
- 面试题5:从尾到头打印链表
- 面试题5-从尾到头打印链表
- 剑指offer面试题 从尾到头打印链表
- 关于js异步加载的理解
- 小游戏
- poj-3898 Software Industry Revolution DP
- VS2005升级VS2010遇到的问题解决
- 高斯滤波与SIFT特征检测
- 面试题4:从尾到头打印链表
- 生产者消费者问题(java模拟)
- The Robbery
- MFC ListCtrl控件
- 关于c++的虚函数的一些总结
- 业务逻辑层的设计(三)——事务的考虑
- Qt右击菜单建立
- SQL2008错误
- 关于递归