Data structure and algorithm-linked list inversion

Source: Internet
Author: User

Tag:highlight   using   empty    Stack structure    sharp    head   csharp    access     list reversal    

1. Enter the head node of a linked list, which in turn outputs the value of each node from the end of the head. The
link table node is defined as follows:
struct listnode
      int        M_nkey;
      listnode* m_pnext;
analysis: This is a very interesting face test. The problem and its variants are often seen in the interviews and written questions of major companies.
After seeing this problem, the first reaction is that the output from beginning to end is relatively simple. It is natural to think of the link node in the linked list of the pointer reversal, change the direction of the list. Then you can output it from start to finish.

Now that you think of stacks to implement this function, recursion is essentially a stack structure. So it is natural to think of the use of recursion to achieve. To implement the output linked list, each time we access to 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.

//Recursive method reverse output void printlistreversely (listnode* plisthead) {      if (plisthead! = NULL)      {            if (plisthead- >m_pnext! = NULL)            {                  printlistreversely (plisthead->m_pnext);            }            Print this node            printf ("%d", Plisthead->m_nkey);}      } //Stack method reverse output void Printlistusingstack (ListNode *plisthead) {    stack s;;    ListNode *p;    P=plisthead;   do{       push (&s,p->m_nkey);       p=p->m_pnext;   } while (p!=null);   while (! IsEmpty (&s))   {       printf ("%d/n", Pop (&s));}   }

Data structure and algorithm-linked list inversion

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: 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.