您的位置:首页 > 其它

递归方法反转链表

2014-08-25 21:22 260 查看
<span style="font-size:18px;">#include <iostream>
#include <time.h>
#include <string>
using namespace std;

//单链表反转

struct node
{
int data;
node *next;
};

void Create(node * &head)
{
int data;
cin>>data;
node *p1,*p2;
while(data!=-1)
{
if(head==NULL)
{
head=new node;
head->data=data;
head->next=NULL;
p1=head;
}
else
{
p2=new node;
p2->data=data;
p1->next=p2;
p1=p2;
p1->next=NULL;

}
cin>>data;
}
}
void Print(node *head)
{
while(head!=NULL)
{
cout<<head->data<<' ';
head=head->next;

}
}

node *Reverse(node *p,node *&head)
{
if(p->next==NULL)
{
head->next=NULL;
head=p;
return p;
}
else
{
node *tmp=Reverse(p->next,head);
tmp->next=p;
return p;
}
}
void main()
{
node *head=NULL;
Create(head);
Reverse(head,head);
Print(head);

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