insert new node at any index within a single linked list

前端 未结 2 1179
栀梦
栀梦 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

    0 讨论(0)
  • 2021-01-15 23:41

    you have to deal with one special situation when index == 0, the headRef will need to be updated. or if index is greater than the number of elements in the list. The insert will fail. Otherwise check out the example code below.

    int insertN(struct node** headRef, int index, int data) {
        /* invalid headRef */
        if (!headRef) {
            return 0;
        }
        /* insert node at index */
        int i;
        struct node* new = (struct node *)malloc(sizeof(*node));
        struct node *scan = *headRef;
        new->data = data;
        new->next = 0;
        /* new head of list */
        if (scan == NULL && index == 0) {
             /* new head node */
             new->next = *headRef;
             *headRef = new;
             return 0;
        }
        /* while not at end of list and not at index */
        for (i = 0; scan != NULL && i <= index; i++) {
            if (i == index) {
                /* move what was here to next node and put in new node */
                new->next = scan->next;
                scan->next = new;
            } else {
                /* advance to next entry in list */
                scan = scan->next;
            }
        }
        /* scan == NULL indicates reached end of list before index */
        return (scan != NULL);
    }
    
    0 讨论(0)
提交回复
热议问题