由于链表在内存中不是连续存储的,所以必须要知道链表头指针的地址。
由于是从尾到头打印,自然而然想到用栈结构实现,因为递归本质上也是一个栈结构,所以也可以用递归实现。
栈结构实现从尾到头打印链表:
struct ListNode
{
int m_nvalue;
ListNode* m_pNext;
};
void PrintListReversingly(ListNode* pHead)
{
std::stack<ListNode*> node;
ListNode* pNode = pHead;
while(pNode -> m_pNext != nullptr)
{
node.push(pNode);
pNode = pNode -> m_pNext;
}
while(!node.empty())
{
pNode = node.top();
printf("%d\t",pNode -> m_nvalue);
node.pop();
}
}
递归实现从尾到头打印链表:
void PrintListReversingly_Recrusively(ListNode* pHead)
{
if (pHead != nullptr)
{
if (pHead -> m_pNext != nullptr)
{
PrintListReversingly_Recrusively(pHead ->m_pNext);
}
printf("%d\t",pHead ->m_pNext);
}
}
一般不推荐用递归,效率太低!