For example, if a-> B-> C-> D-> E-> F-> null is reversed in a single-chain table, F-> E-> D-> C-> B-> A is obtained. -> null
【AlgorithmI]
The most common algorithm involves three nodes in the reversal process: the forward node (PPRE), the current node (pcur), and the next node (pnext ), of course, in the process of Algorithm Implementation, sometimes adding more variables can get twice the result with half the effort. Here we define an additional pointer variable to save the reversed header node (preversedhead ), the process of inversion is actually to point the next pointer of the current node to the previous node, and the next node is used to ensure that the linked list is not broken. Therefore, three pointers are preset and move forward step by step until null, then return the End Node Address.
The time complexity is O (n ).
Listnode * reverselinklist (listnode * phead) {linknode * preversedhead = NULL; linknode * PPRE = NULL; linknode * pcur = phead; linknode * pnext = NULL; while (pcur! = NULL) {pnext = pcur-> next; // if the successor node of the current node is null, the current node is the end node if (pnext = NULL) {preversedhead = pcur; break;} pcur-> next = PPRE; PPRE = pcur; pcur = pnext;} return preversedhead ;}
Algorithm 2]
Recursion.
Advantages:CodeSimplified.
Disadvantage: it is hard to understand, and a long linked list may cause stack overflow.