<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;
}
剑指offer5,从尾到头打印链表
最新推荐文章于 2023-06-22 17:10:40 发布