One-way linked list inversion algorithm-recursive version and iteration version

Source: Internet
Author: User

Recently, when doing a pen test, encountered a programming problem: one-way list reversal algorithm. A moment of tension, did not write out on the early hand, but after handing over the volume to think out ...

Originally wanted to come out is the recursive version, unfortunately did not be able to do the tail recursion, and later figured out the iteration version. Later with the actual compilation run test again, can run normally.

The recursive version is inspired by the very concise implementation of the fast sorting algorithm in the Haskell guide, whose idea is to split the unidirectional list into the head and tail. Where the head refers to the first node of the list, and the tail is the sub-linked list after the first node is removed. By recursive method, the sub-list continues to be divided into the head and tail, until the tail refers to the remaining node, unable to continue splitting, then the head and tail position exchange, return to the tail, and then the previous head to the back of the tail, continue to return the new tail, and so on, until the entire recursive completion.

The idea of iteration is to use three pointers (first, now, next) to assist in the order of adjustment. Each iteration (i.e., one node at a time), splits the single-linked list dynamically into two parts that are reversed and reversed. After each iteration, the inverted list becomes longer, and the list before the reversal is shortened until the list length is 0 before the reversal, the reversal is complete, and the inverted list is returned. The whole idea is a bit like bubbling sort, dividing the sequence (linked list) into an ordered area (the inverted part) and the unordered area (the former part of the reversal), but only one traversal of the entire unidirectional list.

It is important to note that the first iteration begins with the second node of the one-way list. The first node, by default, is the inverted node, and the tail node is reversed, in order to avoid loop-induced dead loops, you need to set the pointer to NULL for the next node that the node points to.

These three pointers function as follows:

    • The first pointer always points to the top node of the inverted list;
    • The now pointer points to the first node of the list that is currently traversed before the reversal;
    • The next pointer points to the next node of the now node and avoids the loss of a reference to the linked list before reversal when Now->next points to the first node of the inverted list.

The key data structures are as follows:

1 struct _node {2     int data; 3     struct _node * next; 4 } Node;

The recursive version of the inversion algorithm code is as follows:

1Node * NODE_REVERSE (node *node) {2     if(node = = NULL)returnNULL;3     if(Node->next = = NULL)returnnode;4Node * n = node_reverse (node->next);5     if(n! =NULL) {6N->next =node;7Node->next =NULL;8     }9     returnnode;Ten}

In fact, this recursive version of the inversion algorithm has a small flaw: that is, the entire recursive completion, the returned node is the parameters passed in. That is, if the first node of the one-way list is passed before the reversal, the node is returned, and the node is the tail node of the inverted one-way list (because of the reversal, the end-to-end exchange). Therefore, when using, it is necessary to do some trivial work to compensate for the defect. That is, you need to go through the one-way list before use, find the tail node and reference it with a pointer ... Actually can improve this piece of code to fix this small flaw, put these trivial work to this function to complete, namely add an if branch of thing, I am lazy to write. The iteration version is not the problem, and the efficiency is slightly higher.

The iterative version of the inversion algorithm code is as follows:

1Node * NODE_REVERSE_V2 (node*node) {2     if(node = = NULL)returnNULL;3     if(Node->next = = NULL)returnnode;4 5Node *first = node;//always point to the header of the new list. 6Node *now = node->Next;7Node *next = now->Next;8First->next = NULL;//The first node becomes the tail node, and the next node of the tail node is empty to prevent the loop. 9      Do {TenNext = now->Next; OneNow->next =First ; AFirst =Now ; -now =Next; -} while(Next! =NULL); the  -     returnFirst ; -}

The test code is as follows:

1 voidPrintnode (Node *node) {2     if(Node! =NULL) {3printf"%d", node->data);4     }5 }6 7 intMain ()8 {9LinkedList *l =list_create ();Ten      for(intI=0; I<20; i++) { One list_append (L, i); A     } - List_foreach (L, Printnode); -printf"\ n"); the List_foreach (List_reverse (L), printnode); -printf"\ n"); - List_foreach (LIST_REVERSE_V2 (L), printnode); -printf"\ n"); +     return 0; -}

The output is as follows:

Full code Download:

reverse.7z

One-way linked list inversion algorithm-recursive version and iteration version

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.