您的位置:首页 > Web前端

剑指offer5,从尾到头打印链表

2016-05-05 10:54 459 查看
<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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: