Reverse of linked list

Source: Internet
Author: User

(1) reverse of the linked list

The original linked list retains a head node, which can be used to traverse the content of each node in the table, use two pointers to direct the content pointer in the linked list to the next node, and change it to the previous node. This will reverse the linked list!

# Include <stdio. h>

# Include <stdlib. h>

Struct llist

{

Int num;

Struct llist * next;

};

Typedef struct llist node;

Typedef node * llink;

 

Void printllist (llink ptr)

{

While (ptr! = NULL)

{

Printf ("[% d]", ptr-> num );

Ptr = ptr-> next;

}

Printf ("\ n ");

}

Llink createllist (int * array, int len)

{

Llink head;

Llink ptr, ptr1;

Int I;

Head = (llink) malloc (sizeof (node ));

If (! Head)

Return NULL;

Head-> num = array [0];

Head-> next = NULL;

Ptr = head;

For (I = 1; I <len; I ++)

{

Ptr1 = (llink) malloc (sizeof (node ));

If (! Ptr1)

Return NULL;

Ptr1-> num = array [I];

Ptr-> next = NULL;

Ptr-> next = ptr1;

Ptr = ptr-> next;

}

Return head;

}

// Implementation process of chain table Inversion

Llink invertllist (llink head)

{

Llink mid, last;

Mid = NULL;

While (head! = NULL)

{

Last = mid;

Mid = head;

Head = head-> next;

Mid-> next = last;

}

Return mid;

}

 

Void freellist (llink head)

{

Llink ptr;

While (head! = NULL)

{

Ptr = head;

Head = head-> next;

Free (ptr );

}

}

Int main ()

{

Int llist [6] = {1, 2, 3, 4, 5, 6 };

Llink head;

 

Head = createllist (llist, 6 );

If (! Head)

{

Exit (1 );

}

Printllist (head );

Head = invertllist (head );

Printllist (head );

Printllist (head );

Return 0;

}

Share:

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.