---
# System prepended metadata

title: Insert a Node at the Tail of a Linked List
tags: [HackerRank, Linked List, Easy]

---

思考:
1.如果是一個空鏈結則新節點成為head
2.需要回傳這一個鏈結串列的head，代表要用一個point
3.需要先new新節點在接上


```c++=
SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
    //creat a new node
    SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
    if(head == NULL){
        head = newNode;
        return head;
    }else{
        //find tail node
        SinglyLinkedListNode* ptr = head;
        while(ptr->next != NULL){
            ptr = ptr->next;
        }
        //find tail node
        ptr->next = newNode;
        return head;
    }
}

```



```c++=
// Complete the insertNodeAtTail function below.

/*
 * For your reference:
 *
 * SinglyLinkedListNode {
 *     int data;
 *     SinglyLinkedListNode* next;
 * };
 *
 */
SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
    //creat new node
    SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);

    if (!head) {

        head = newNode;
    } else {
        SinglyLinkedListNode* ptr = head;
        while (ptr->next != NULL) {
            ptr = ptr->next;
        }
        ptr->next = newNode; 
    }

    return head;
}

```