Sometimes, we need to reverse the singly linked list, the following code realizes the reverse operation of the singly linked list.
#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; //The function of reversing the single-linked list with linear time complexity, the head node of the linked list can be passed in to reverse the entire single-linked list 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; }
These codes have linear time complexity for the reverse operation with a singly linked list. O(n).
Please comment if there are mistakes.