Insert linked list nodes in C Language

Source: Internet
Author: User

Insert linked list nodes in C Language

Adding, deleting, modifying, and querying a linked list are the most basic operations. In my previous blog "delete linked list nodes in C Language", I deleted a node in the linked list. Here we want to insert a node at a certain position.

The core code is as follows:

Node * InsertToPosition (Node * pNode, int pos, int x) {if (pos <0 | pos> sizeList (pNode) {printf ("% s function execution, invalid pos = % d. Failed to insert data \ n ",__ FUNCTION __, pos); return pNode;} Node * pMove; Node * pInsert; pInsert = (Node *) malloc (sizeof (Node); memset (pInsert, 0, sizeof (Node); pInsert-> next = NULL; pInsert-> element = x; pMove = pNode; int I = 1; // here we separately consider pos = 0. if (pos = 0) {pInsert-> next = pNode; pNode = pIns Ert; printf ("% s FUNCTION execution, insert x = % d in pos = % d success \ n" ,__ FUNCTION __, pos, x); return pNode ;} while (pMove! = NULL) {if (I = pos) {pInsert-> next = pMove-> next; pMove-> next = pInsert; printf ("% s function execution, insert x = % d into pos = % d successfully \ n ",__ FUNCTION __, pos, x); break;} I ++; pMove = pMove-> next ;} return pNode ;}

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.