해커랭크(HackerRank)

Reverse a linked list

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


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
/*
  Reverse a linked list and return pointer to the head
  The input list will have at least one element  
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Reverse(Node *head)
{
  // Complete this method
    Node *tail, *node;
    tail = NULL;
    while (head != NULL) {
        // 다음 노드를 넣어 준다.
        node = head->next;
        // head->next 는 tail 을 가리키게 하고
        head->next = tail;
        // tail 은 현재 head 를 가리키게 한다.
        tail = head;
        // head 와 node 를 swap 
        head = node;
    }
    return tail;
}
cs

반응형