只要让头指针一直指向新创建的节点,且新建立的节点指向上一个节点,就能指向最后一个节点,就能从最后一个逆序输出
#include<iostream>
using namespace std;
struct node
{
char a;
node * next;
};
void creat(node *& head);
void display(node *& head);
int main()
{
node * head=NULL;
creat(head);
display(head);
}
void creat(node *& head)
{
node * s,* p;
char ch;
cin.get(ch);
while(ch!='\n')
{
s=new node;
//创建新节点
s->a=ch;
s->next=head;
//第一个节点指向null,其他都指向上一个节点,因为head套在上一个节点上,所以指向head
head=s;
//头指针始终指向最后一个节点
cin.get(ch);
}
return ;
}
void display(node *& head)
{
while(head)
{
cout<<head->a;
head=head->next;
}
cout<<endl;
}