Use Data Structure stack or Recursion
1. Use Stack
# Include <iostream> # include <stack> using namespace STD; typedef struct listnode {int key; structlistnode * pnext;} * pnode, node; void createnode (pnode & phead) {bool isfirst = true; int temp; scanf ("% d", & temp); pnode P = phead, Q; while (temp! = 0) {q = (pnode) malloc (sizeof (node); q-> key = temp; q-> pnext = NULL; If (isfirst) {P = phead = Q; isfirst = false;} else {P-> pnext = Q; P = Q;} scanf ("% d", & temp );} cout <"the original linked list is:" <Endl; P = phead; while (p) {cout <p-> key <""; P = p-> pnext ;}} void printlistreverse (const pnode phead) {stack <pnode> Vep; pnode P = phead; while (p) {VEP. push (p); P = p-> pnext;} while (! VEP. empty () {P = VEP. top (); cout <p-> key; VEP. pop () ;}} int main () {pnode phead = NULL; createnode (phead); printlistreverse (phead); Return 0 ;}
Running result:
2 Recursion
# Include <iostream> # include <stack> using namespace STD; typedef struct listnode {int key; structlistnode * pnext;} * pnode, node; void createnode (pnode & phead) {bool isfirst = true; int temp; scanf ("% d", & temp); pnode P = phead, Q; while (temp! = 0) {q = (pnode) malloc (sizeof (node); q-> key = temp; q-> pnext = NULL; If (isfirst) {P = phead = Q; isfirst = false;} else {P-> pnext = Q; P = Q;} scanf ("% d", & temp );} cout <"the original linked list is:" <Endl; P = phead; while (p) {cout <p-> key <""; P = p-> pnext;} void printlistreverse (const pnode phead) {If (phead = NULL) return; printlistreverse (phead-> pnext ); cout <phead-> key;} int main () {pnode phead = NULL; createnode (phead); printlistreverse (phead); Return 0 ;}
Running result: