Title: Enter the head node of a linked list, which in turn prints the value of each node from the end of the head. (Cannot change the structure of the linked list)
struct ListNode
{
int M_nkey;
listnode* M_pnext;
};
The order of traversal in the subject is from the beginning to the end, but the output is from the head. So the "LIFO" feature of the problem symbol stack.
It is therefore possible to use stacks to implement this order. Each time a node is passed, the node is placed in the stack, and when the entire list is traversed, the value of the node is output from the top of the 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\t", Pnode->m_nvalue);
Nodes.pop ();
}
}
Solution Two
Because recursion is essentially a stack structure, it is natural to think of the recursive return implementation. To implement the output linked list, each time we access a node, we first recursively output the node behind it, and then output the node itself, so that the output of the linked list is reversed.
void printlistreversingly_recursively (listnode* phead)
{
if (phead! = NULL)
{
if (phead->m_pnext! = NULL)
{
Printlistreversingly_recursively (Phead->m_pnext);
}
printf ("%d\t", Phead->m_nvalue);
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Print linked list from tail to head