您的位置:首页 > 职场人生

剑指offer——面试题5:从尾到头打印链表

2016-11-25 10:33 483 查看






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\t", 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\t", pHead->m_nValue);
}
}






void Test1()
{
printf("\nTest1 begins.\n");

ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);

ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);

Test(pNode1);

DestroyList(pNode1);
}

// 只有一个结点的链表: 1
void Test2()
{
printf("\nTest2 begins.\n");

ListNode* pNode1 = CreateListNode(1);

Test(pNode1);

DestroyList(pNode1);
}

// 空链表
void Test3()
{
printf("\nTest3 begins.\n");

Test(NULL);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: