How to reverse a one-way list using recursive and non-recursive methods

Source: Internet
Author: User
The following is a detailed analysis of the use of recursive and non-recursive methods to reverse one-way lists of examples, the need for friends can come to reference the next

Problem:
Give a one-way list and turn it upside down. For example: a-> b-> c->d in turn is D-> C-> b-> A.

Analysis:
Suppose the structure of each node is:

Copy Code code as follows:


class Node {


char value;


Node Next;


}


Because the "next" value of each node needs to be updated when the list is reversed, we need to save the next value before updating the next value, otherwise we cannot continue. So, we need two pointers to point to the previous node and the next node, each time after the current node "Next" value is updated, move the two nodes down until the last node is reached.

The code is as follows:

Copy Code code as follows:


Public node reverse (node current) {


//initialization


Node previousnode = null;


Node nextnode = null;





while (current!= null) {


//save the next node


NextNode = Current.next;


//update The value of "next"


current.next = Previousnode;


//shift The Pointers


Previousnode = current;


current = NextNode;


 }


return previousnode;


}


The code above is a recursive method, and this problem can be solved recursively. the code is as follows:

Copy Code code as follows:


Public node reverse (node current)


 {


if (current = null | | current.next = NULL) return to current;


Node nextnode = Current.next;


current.next = null;


Node reverserest = reverse (nextnode);


Nextnode.next = current;


return reverserest;


 }


The recursive approach is actually very clever, it uses recursion to go to the end of the list, and then update each node next value (code penultimate sentence). In the above code, the value of reverserest does not change to the last node of the list, so, after the inversion, we can get the head of the new list.

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.