劍指offer5,從尾到頭列印連結串列
阿新 • • 發佈:2018-12-30
<pre name="code" class="cpp">#include "stdafx.h" #include<iostream> #include<string> #include<stdlib.h> #include<stdio.h> #include<stack> using namespace std; struct Listnode { char key; Listnode* next; }; void creatlist(Listnode *&head) { Listnode *p=head; while(1) { char s; cin>>s; if(s!='#') { Listnode *newnode=new Listnode; newnode->key=s; newnode->next=NULL; if(head==NULL) { head=newnode; p=head; } else { p->next=newnode; p=newnode; } } else { break; } } } void reverselink(Listnode *&head) { Listnode *p=head; stack <Listnode*>s; while(p!=NULL) { s.push(p); p=p->next; } Listnode *node=s.top(); cout<<node->key; s.pop(); while(!s.empty()) { node=s.top(); cout<<" "<<node->key; s.pop(); } cout<<endl; } int main() { Listnode *head=NULL; creatlist(head); Listnode * p =head; while(p!=NULL) { if(p == head) cout << p->key; else cout << " " << p->key; p=p->next; } cout << endl; reverselink(head); system("pause"); return 0; }