方法1.通过建立一个新链表实现
struct ListNode *reverse(struct ListNode *head)
{
struct ListNode *head1=NULL,*p=NULL;
while(head)
{
p=(struct ListNode*)malloc(sizeof(struct ListNode));//申请内存
p->data=head->data;
p->next=head1; //利用头插法进行逆置
head1=p;
head=head->next; //实现原链表的移动
}
return head1;
}
方法2.就地逆转
利用循环,从头进行处理,每轮循环将原链表分为已逆置q链,和待逆置p链,然后循环将待逆转的p链第一个元素通过头插法插到q链的表头处直至循环结束。(个人认为与选择排序很像)
struct ListNode *reverse(struct ListNode *head)
{
struct ListNode *p,*q,*head_p;
p=head,q=NULL; //初始化
while(p!=NULL)
{
head_p=p->next; //保存新p链表头
p->next=q; //头插
q=p; //更新q链
p=head_p; //更新p链
}
return q;
}
方法3.递归逆置
struct ListNode *reverse( struct ListNode *head )
{
struct ListNode *p;
if (head==NULL||head->next==NULL) //递归出口
return head;
p=reverse(head->next);
head->next->next=head;
head->next=NULL;
return p;
}