单链表的反转算法

来源:互联网 发布:申威26010 知乎 编辑:程序博客网 时间:2024/06/05 20:10

经典单链表反转问题,不增加额外空间消耗,去对单链表进行翻转,输出逆序后的链表。

具体执行过程如下所示:


上图显示了单链表翻转算法的步骤示意图,

核心代码如下:

while head->next!=NULL    head->next=pre;    pre=head;    head=next;    next=head->next;

说明:上面的代码最后一个节点处会出现断层,改正如下

while head->next!=nullptr        head->next=pre;        pre=head;        head=next;        if head->next==nullptr                head->next=pre;                break;        next=head->next;



原创粉丝点击