해커랭크(HackerRank)

Insert a Node at the Tail of a Linked List

cepiloth 2018. 8. 19. 17:22
반응형


1. 문제


2. 알고리즘

키워드 - 구현, 링크리스트


3. 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Insert(Node *head,int data)
{
  // Complete this method
    Node* node = new Node();
    node->data = data;
    node->next = NULL;
    
    if (head == NULL) {
        head = node;
        return head;
    }
    
    Node* first = head;
    while (head->next) head = head->next;
    head->next = node;
    return first;
}
cs


반응형