您的位置:首页 > 其它

单链表的逆置

2016-05-06 10:53 239 查看
最近看了面试常问到的单链表逆置问题,做了一下总结。

第一种方法,使用三指针。

node *reverse(node *head)

{

node *p1,*p2,*p3;

if(head==NULL||head->next==NULL)

return head;

p1=head,p2=p1->next;

while(p2)

{

p3=p2->next;

p2->next=p1;

p1=p2;

p2=p3;

}

head->next=NULL;

head=p1;

return head;

}



最后执行完循环后,记得让head->next = NULL; 让P1做head节点,即可实现逆置。

第二种方法,递归。

LNode* ReverList1(LNode* head)

{

if (head == NULL)

return NULL;

if (head->next == NULL)

{

return head;

}

LNode* Node = head; //保留上一个结点

LNode* Nex = head->next;

LNode* HeadNode = ReverList1(Nex);

Nex->next = Node; //逆置

Node->next = NULL; //这句必须有,否则会产生循环链表

return HeadNode;//返回逆置链表的尾结点

}

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