[Linked list] Reverse a single-chain table

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.