C++ 实现对单链表的反转算法

有个时候,我们需要对单链表进行反转操作,如下代码实现了对单链表的反转操作。

#include "iostream"
using namespace std;

struct node{
    int x;
    struct node *next;
    node(int x)
    {
        this->x=x;
        this->next= nullptr;
    }
};
typedef struct node Node;
//线性时间复杂度的反转单链表的函数,传入链表的头结点就可以对整个单链表进行反转
Node * reverseList(Node *head){
    Node *p1=head;
    Node *p2=p1->next;
    Node *p3=p2->next;

    while (p3!= nullptr)
    {
        p2->next=p1;
        p1=p2;
        p2=p3;
        p3=p3->next;
    }
    p2->next=p1;
    head=p2;
    return head;
}
int main()
{
    return 0;
}

这些代码对有个单链表的反转操作是线性时间复杂度。O(n).

如有错误请评论。

猜你喜欢

转载自blog.csdn.net/weixin_53064820/article/details/129879299