在cnbeta上看到的,就自己写一写,练下链表和递归。
#include <iostream>
#include <cstdio>
using namespace std;
struct Node
{
Node(int n){
num=n;
next=NULL;
}
int num;
Node* next;
};
Node* head;
Node* tail(Node* p)
{
if(p==NULL||p->next==NULL) return p;
return tail(p->next);
}
void travel(Node* p)
{
if(p==NULL) return;
cout<<p->num;
if(p->next!=NULL){
cout<<"->";
travel(p->next);
}
}
Node* reverseSL(Node* p)
{
if(p==NULL) return NULL;
if(p->next==NULL) return p;
Node* t=reverseSL(p->next);
Node* tt=tail(t);
if(tt!=NULL) {tt->next=p;p->next=NULL;}
return t;
}
int main()
{
freopen("data.dat","r",stdin);
int num;
cin>>num;
head=new Node(num);
Node* p=head;
while(cin>>num){
p->next=new Node(num);
p=p->next;
}
cout<<"origin list:"<<endl;
travel(head);
head=reverseSL(head);
cout<<endl;
cout<<"after reverse:"<<endl;
travel(head);
return 1;
}