Recursive/non-Recursive Algorithms in reverse order of linked lists

Source: Internet
Author: User

C code
/**
* Recursive/non-recursive algorithms of the Reverse Sequence of the linked list
*/
# Include <stdio. h>
Typedef int Item;
Typedef struct node
{
Item item;
Struct node * next;
} Node, * List;
 
/* Reverse1 ~ 2 is a reverse algorithm without leading nodes */
List reverse1 (List l)
{
Node * p1, * p2;
If (l = NULL)
Return l;
P1 = l-> next;
L-> next = NULL;
While (p1! = NULL ){
P2 = p1-> next;
P1-> next = l;
 
L = p1;
P1 = p2;
}
Return l;
}
List reverse2 (List l)
{
If (l = NULL | l-> next = NULL)
Return l;
Node * p = reverse2 (l-> next );
L-> next = l;
L-> next = NULL;
Return p;
}
/* Reverse3 ~ 4 is the reverse algorithm of the linked list of leading nodes */
Void reverse3 (List l)
{
Node * p1, * p2, * p3;
If (l = NULL | l-> next = NULL)
Return;
P1 = l-> next;
P2 = p1-> next;
P1-> next = NULL;
While (p2! = NULL ){
P3 = p2-> next;
P2-> next = p1;
P1 = p2;
P2 = p3;
}
L-> next = p1;
}
Void reverse4 (List l, Node * first)/* this algorithm is not very good. You need to Judge l outside the function! = NULL */
{
If (first = NULL | first-> next = NULL ){
L-> next = first;
Return;
}
Reverse4 (l, first-> next );
First-> next = first;
First-> next = NULL;
}

Author "Ackerman's Blog"
 

Related Article

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.