反转链表的递归实现和非递归实现:
#include "iostream"
#include "stdlib.h"
using namespace std;
typedef struct Node{
int value;
struct Node* next;
}Node;
Node* create_list(Node* &last)
{
int data;
Node* head =NULL,*cur;
cin>>data;
while (data !=-1)
{
Node* pNode =(Node*)malloc(sizeof(Node));
pNode->value =data;
pNode->next =NULL;
if (head==NULL)
{
head =pNode;
cur =pNode;
}
else
{
cur->next =pNode;
cur =cur->next;
last =cur;
}
cin>>data;
}
return head;
}
void print(Node* head)
{
Node* cur =head;
while(cur)
{
cout<<cur->value<<" ";
cur =cur->next;
}
cout<<endl;
}
//递归反转链表
Node* reverse(Node* head)
{
if (head->next ==NULL)
{
return head;
}
Node* temp =reverse(head->next);
temp->next =head;
head->next =NULL;
return head;
}
//非递归反转链表
Node* reverlist(Node* head)
{
Node* pre =head;
Node* cur =pre->next;
head->next =NULL;
while(cur)
{
Node* temp =cur->next;
cur->next =pre;
pre =cur;
cur =temp;
}
return pre;
}
void main()
{
Node* head,*last;
cout<<"输入结点值:\n";
head =create_list(last);
print(head);
// reverse(head);
reverlist(head);
print(last);
}