#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
一,迭代实现
struct Node* Reverse(struct Node* head)
{
struct Node*pre,*current,*next;
current=head;
pre=NULL;
while(current!=NULL)
{
next=current->next;//永远都保留下一项的地址
current->next=pre;//改变连接方向
pre=current;//更新pre,current
current=next;
}
head=pre;//循环的最后current为NULL,pre为新的头结点
return head;
}
二,递归实现
void reserve(struct Node* p)
{
if(p==NULL)
{
head=p;
return;
}
reverse(p->next);//递归
struct Node* q=p->next;
q->next=p;
p->next=NULL;
}
这里主要需要理解递归;
1.在到达基准情况之前,p->next以堆栈的方式存储,
2.基准情况先执行if语句,
3.依次出栈再执行递归语句下面的statement。