Print linked list from tail to head

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.