There is an integer one-way linked list A. Please program it in reverse order.

Source: Internet
Author: User

The Code is as follows:

# Include <stdio. h>
# Include <stdlib. h>

Struct lList
{
Int num;
Struct lList * next;
};
Typedef struct lList node;
Typedef node * llink;

Void printllist (llink PTR) // output of the linked list
{
While (PTR! = NULL)
{
Printf ("[% d]", PTR-> num );
PTR = PTR-> next;
}
Printf ("\ n ");
}

// Create a linked list
Llink createllist (int * array, int Len)
{
Llink head; // start pointer of the linked list
Llink PTR, ptr1;
Int I;

// Create the first node
Head = (llink) malloc (sizeof (node); // allocate memory
If (! Head) // check the pointer
{Return NULL ;}
Head-> num = array [0]; // create node content
Head-> next = NULL; // you can specify the initial value of a pointer.
PTR = head; // point the PTR to the linked list.
For (I = 1; I <Len; I ++) // create other node Loops
{
Ptr1 = (llink) malloc (sizeof (node ));
If (! Ptr1)
{
Return NULL;
}
Ptr1-> num = array [I]; // create node content
Ptr1-> next = NULL;
PTR-> next = ptr1;
PTR = PTR-> next;
}
Return head;
}

// Reverse of the linked list
Llink invertllist (llink head)
{
Llink mid, last;
Mid = NULL; // mid is the front node of the head.
While (Head! = NULL)
{
Last = mid; // last is the front node of the MID.
Mid = head;
Head = head-> next; // next node
Mid-> next = last; // mid indicates the forward node's last
}
Return mid;
}

Int main (INT argc, char * argv [])
{
Int lList [6] = {1, 2, 3, 4, 5, 6 };
Llink head;

Head = createllist (lList, 6 );
If (! Head)
{
Printf ("memory allocation failed! \ N ");
Exit (1 );
}
Printf ("original linked list :");
Printllist (head );
Head = invertllist (head );
Printf ("reverse linked list :");
Printllist (head );



System ("pause ");
Return 0;
}

 

 

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.