The simplest way to reverse a one-way linked list

Source: Internet
Author: User

The header of a one-way linked list must be converted into a reverse link after processing, that is, the end of the original linked list is changed to the head of the linked list, and the head of the original linked list is changed to the end of the linked list.

Example: 10-> 20-> 30-> null

Changed to: 30-> 20-> 10-> null after processing

I think the following should be the simplest method in terms of time and space.

Struct list {
Int value;
Struct list * next;
};

Static int reverse (struct list ** PL)
{
Struct list * Header, * TMP;

If (* PL = NULL) return 0;

Header = NULL;
// Add node to header and point to next node.
While (* pl! = NULL) {TMP = * pl; * PL = (* PL)-> next; TMP-> next = header; header = TMP ;}

* PL = header;
Return 1;
}

Test:

Static void print_list (struct list * PL)
{
Struct list * Header = pl;
Printf ("list :");
While (header! = NULL ){
Printf ("% d", header-> value );
Header = header-> next;
}
Printf ("/N ");
}

Int _ tmain (INT argc, _ tchar * argv [])
{
# Define Number 9
Int I = 0;
Int score [number] = {10, 20, 30, 40, 50, 60, 70, 80, 90 };
Struct list * Header, * cur, * TMP;
 
Header = cur = NULL;
// Create list.
While (I <number ){
TMP = (struct list *) malloc (sizeof (struct list ));
TMP-> value = score [I];
TMP-> next = NULL;
If (I = 0)
Header = cur = TMP;
Else {
Cur-> next = TMP;
Cur = cur-> next;
}
I ++;
}
Print_list (header );

Reverse (& header );
Print_list (header );

Reverse (& header );
Print_list (header );

Printf ("Hello, world! /N ");
Getch ();
Return 0;
}


Http://blog.csdn.net/knock/archive/2010/11/26/6036703.aspx

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.