(LeetCode) 206. Reverse Linked List

Reverse Linked List

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : Linked List
  • 난이도 : Easy

Problem

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1

1
2
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2

1
2
Input: head = [1,2]
Output: [2,1]

Example 3

1
2
Input: head = []
Output: []

Constraints

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Solution

Exapnder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun reverseList(head: ListNode?): ListNode? {
var reverse: ListNode? = null
var node = head
while (node != null) {
reverse = ListNode(node.`val`).apply {
next = reverse
}
node = node.next
}
return reverse
}
}

Point of Thinking

  • 임의의 노드를 생성한 뒤, 뒤에서부터 포인터를 연결해주면 끝