# 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);
```

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHM9iSeXI_nXEBO-xeZ%2F-LHMAA5TyKd13H8oxCbI%2Fcc3ec14c-93d5-4692-a8c5-aa592a852a07.png?alt=media\&token=fd09c0cb-ee87-4a7a-a0f9-ffd65994e8a9)

## 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);
```

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHM9iSeXI_nXEBO-xeZ%2F-LHMAG9ww5sv0yiGNotd%2Fff905669-0ee4-4613-8257-15d0a53b967a.png?alt=media\&token=d0624ebe-a0de-4bc2-9fe4-3011e7dd09d5)

## 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);
```

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHM9iSeXI_nXEBO-xeZ%2F-LHMAHxXzUbNbCCubmYi%2F73e0e5c9-cec9-45de-b379-27e10430788a.png?alt=media\&token=a57a8761-7cc6-47c2-b8b1-c53d255ff07e)

##
