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; S.top=0; 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