insert new node at any index within a single linked list

前端 未结 2 1181
栀梦
栀梦 2021-01-15 23:03

how would i go about creating a function that will allow me to insert a new node at any index within a linked list? here\'s the struct:

struct node {
    int         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-15 23:31

    As you can see in the image below, you need to insert the node between two nodes.

    The other 3 cases are

    • Inserting at the start of the list
    • Inserting in the middle of list
    • Inserting at the end of the list.

    Maintain a count and loop through all the elements in the list. This count will help you keep track of the index.

    Once you reach the node, where you have to insert the new node

    • Create the new node
    • Point the next pointer of the prev node to new node.
    • Point the next pointer of the new node to current node.

    Full Source Code available here

    enter image description here

提交回复
热议问题