C++テールからチェーンテーブルを印刷(剣指offer面接問題6)
次はPrintListInReversedOrderです.hファイル、二つの方法で
次はPrintListInReversedOrderです.cppファイル、メイン関数を含む
テスト結果は次のとおりです.
// 6:
// : , 。
#include
#include
#include
using namespace std;
//
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
/********************************************************/
//
// , , 。
// , , 。
// “ ”, 。 ,
// 。 , ,
// , :
/********************************************************/
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stacknodes;
ListNode* pNode = pHead;
while (pNode != nullptr)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while (!nodes.empty())
{
pNode = nodes.top();
cout << pNode->m_nValue << " ";
nodes.pop();
}
cout << endl;
}
/**************************************************************/
// , ,
// 。 ,
// , , ,
// 。
/**************************************************************/
void PrintListReversingly_Recursively(ListNode* pHead)
{
if (pHead != nullptr)
{
if (pHead->m_pNext != nullptr)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}
/*printf("%d\t", pHead->m_nValue);*/
cout << pHead->m_nValue << " ";
}
}
次はPrintListInReversedOrderです.cppファイル、メイン関数を含む
#include
#include
#include"PrintListInReversedOrder.h"
using namespace std;
int main()
{
ListNode* pHead = new ListNode();
ListNode *pNew, *pTemp;
pTemp = pHead;
int a[5] = { 1, 4, 2, 5, 6 };
for (int i = 0; i < 5; i++)
{
pNew = new ListNode;
pNew->m_nValue = a[i];
pNew->m_pNext = NULL;
pTemp->m_pNext = pNew;
pTemp = pNew;
}
// , pHead {0, 1, 4, 2, 5, 6}, 0
ListNode *temp = pHead->m_pNext;//
cout << " :" << endl;
PrintListReversingly_Iteratively(temp);
cout << " :" << endl;
PrintListReversingly_Recursively(temp);
cout << endl;
return 0;
}
テスト結果は次のとおりです.
:
6 5 2 4 1
:
6 5 2 4 1
. . .