翻转单向链表

来源:互联网 发布:nero burn for mac 编辑:程序博客网 时间:2024/05/18 03:12

在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;}


原创粉丝点击