Uses iteration (non-recursion) and recursion to reverse the single-chain table

Source: Internet
Author: User

Uses iteration (non-recursion) and recursion to reverse the single-chain table

I have been talking about it for a long time, but many local Interviews still like to ask this question. In actual projects, it seems to be of little use. Why should I select a single-chain table for reverse storage? Why not use list (in C ++) or iterator (in any language )? Or push all the data into the stack and then pop up one by one. It's boring to say so much. See why I am opposed to pure algorithm interview in cool shell.

Iteration (non-recursion)AlgorithmDescription:

Set two temporary pointers, Prev and next, to mark the frontend and successor of the current node, direct the next pointer of the current node to the frontend, replace the frontend pointer with the current node, and replace the current node with next, move to the "back" until the linked list is empty (next is null ).

C/C ++ implementation:

 

 1 Typedef Struct  _ Node  2   { 3       Struct _ Node * Next;  4       Int  Data;  5   } List;  6   7 List * reverse (list * Head)  8   {  9       If (List = Null) 10           Return  ;  11   12 List * pre = Head;  13 List * cur = head-> Next;  14 List * Ne;  15       While (Cur! = Null)  16   {  17 Ne = cur-> Next;  18 Cur-> next = Pre;  19 Pre = Cur;  20 Cur = Next;  21   }  22 Head-> next = NULL;  23 Head = Pre;  24  25       Return  Head;  26 }

 

Recursive Algorithm Description: to sort the current node in reverse order, first sort its successor nodes in reverse order, and then point the next of the last node in reverse order to the current node.

C/C ++ implementation:

 

 1 List * recurreverse (list * P, list * Head)  2   {  3       If (P = NULL | p-> next = Null)  4  {  5 Head = P;  6           Return  P;  7   }  8       Else  9   {  10 List * q = reverse (p-> Next, head );  11 Q-> next = P; 12           Return  P;  13   }  14 }

 

.

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.