面试题5
链表结构:
struct ListNode { int m_nValue; ListNode* m_pNext; };
栈:
注意栈中的类型一定是指针类型,因为每次push进去的是一个指针
#include <stack> void PrintListReversingly_Iteratively(ListNode* pHead) { std::stack<ListNode*> nodes; ListNode* pNode = pHead; while(pNode != NULL) { nodes.push(pNode); pNode = pNode->m_pNext; } while(!nodes.empty()) { pNode = nodes.top(); printf("%d ", pNode->m_nValue); nodes.pop(); } }
递归:
void PrintListReversingly_Recursively(ListNode* pHead) { if(pHead != NULL) { if (pHead->m_pNext != NULL) { PrintListReversingly_Recursively(pHead->m_pNext); } printf("%d ", pHead->m_nValue); } }