Linked list: Insert Node

1.從最前面插入

    struct Node** insert(Node **first, Node *ptrBeforeNode, int data)
    {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->next = NULL;
        if(ptrBeforeNode == NULL){              // 插入在首節點之前
            newNode->next = *first;
            *first = newNode;
        }else{
            if(ptrBeforeNode->next == NULL)     // 插入在尾節點之後
                ptrBeforeNode->next = newNode;
            else{                               // 插入在指定節點之後
                newNode->next = ptrBeforeNode->next;
                ptrBeforeNode->next = newNode;
            }
        }
    }

    insert(&first, NULL, 10);

2.從中間插入

struct Node** insert(Node **first, Node *ptrBeforeNode, int data)
    {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->next = NULL;
        if(ptrBeforeNode == NULL){              // 插入在首節點之前
            newNode->next = *first;
            *first = newNode;
        }else{
            if(ptrBeforeNode->next == NULL)     // 插入在尾節點之後
                ptrBeforeNode->next = newNode;
            else{                               // 插入在指定節點之後
                newNode->next = ptrBeforeNode->next;
                ptrBeforeNode->next = newNode;
            }
        }
    }

    insert(&first, NULL, 10);

3.從最後面插入

struct Node** insert(Node **first, Node *ptrBeforeNode, int data)
    {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->next = NULL;
        if(ptrBeforeNode == NULL){              // 插入在首節點之前
            newNode->next = *first;
            *first = newNode;
        }else{
            if(ptrBeforeNode->next == NULL)     // 插入在尾節點之後
                ptrBeforeNode->next = newNode;
            else{                               // 插入在指定節點之後
                newNode->next = ptrBeforeNode->next;
                ptrBeforeNode->next = newNode;
            }
        }
    }

    insert(&first, NULL, 10);

Last updated