【算法分析】
利用头插法构建单链表后,若从头结点开始遍历单链表,则输出的值的顺序与输入时恰好相反。因此,这个性质常被加以利用,实现序列的逆序输出。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
struct Node {
char data;
Node *next;
};
void nixu(Node *L,int n) {
L=new Node;
L->next=NULL;
for(int i=0; i<n; i++) {
Node *p;
p=new Node;
cin>>p->data;
p->next=L->next;
L->next=p;
}
for(int i=0;i<n;i++){
cout<<L->next->data<<" ";
L->next=L->next->next;
}
}
int main() {
int n;
cin>>n;
Node *p;
nixu(p,n);
return 0;
}
/*
in:
7
a b c d e f g
out:
g f e d c b a
*/