Create a linked list using the head plug and tail plug

Source: Internet
Author: User

Be sure to understand the insertion methods and ideas,

I. Head Insertion Method: first fix a head pointer and insert the first node: Insert a node s behind the head, head-> next = S. Insert second node P: Insert before node s, that is, insert p between head and S. The third node is inserted between node P and head. And so on. The new node is always inserted in front of the previous node.

1. As shown in:

2. Step:


3. Code:

Void headcreatlist (list * l) // create a linked list using the header Insertion Method

{

List * s;

L-> next = NULL;

For (INT I = 0; I <10; I ++)

{

S = (struct list *) malloc (sizeof (struct list ));

S-> DATA = I;

S-> next = L-> next; // assign the address pointed to by L to S;

L-> next = s;

}

}

2. Tail insertion: S is the head node. The head Pointer Points to S, and a node D is inserted after S. Then, modify the head pointer and direct the head to D; then insert the node after the new head, and so on. Note: Changes in the header pointer head.


Code:

Void tailcreatlist (list * l) // create a linked list by means of tail insertion

{

List * s, * R;

R = L;

For (INT I = 0; I <10; I ++)

{

S = (struct list *) malloc (sizeof (struct list ));

S-> DATA = I;

R-> next = s;

R = s;

}

R-> next = NULL;

}

Iii. Summary:

The following figure shows how to insert three nodes into a linked list:


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.