Idea 1:O (n^2).
"Civet cat for Prince", do not change the structure of the list, only Exchange LEN/2 times. However, in this function, the positioning function is used, the positioning function is actually traversing through the entire list, so the overall efficiency is very low to reach O (n^2).
Single-linked list inversion (O (n^2)) void Reverselist (node* head) { int count = Numofnodes (head); Swap for (int i=1; i<=count/2; i++) { node* p1 = Locatenodei (Head, i); node* P2 = Locatenodei (Head, count+1-i); Swap (P1->value, p2->value);} }
Idea 2:O (n).
In the most general case (there is no pre-written auxiliary function, that is, only the head points to a single linked list). O (n) efficiency can be achieved.
The procedure is to traverse with three neighboring pointers, changing the direction of the pointer while traversing. Of course, we should pay attention to the number of linked lists, and the disposal of the chain.
Single-linked list inversion (O (n)) node* ReverseList2 (node* Head) { if (Head==null | | Head->next==null)//empty chain and single node { return Head; } node* p1 = Head; node* P2 = head->next; node* P3 = head->next->next; if (p3==null)//Only two nodes { p1->next = NULL; P2->next = p1; Head = p2; return Head; } else//At least three nodes { p1->next = NULL; while (P3!=null) { p2->next = p1; Three pointers move backward one p1=p2; P2=P3; p3=p3->next; } P2->next = p1; Head = p2; return Head; }}
List of linked list reversal