PS/LeetCode
LeetCode / Linked List / 206번 / Reverse Linked List / JS
KimMinJun
2023. 3. 29. 16:45
Reverse Linked List - LeetCode
Can you solve this real interview question? Reverse Linked List - Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: [https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg] Input: head = [1,2,3,4,5] O
leetcode.com
< 문제 간단설명 >
주어진 Linked List의 노드의 순서를 반대로 바꾸면 되는 문제이다.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head, prev=null) {
if(!head) return prev;
let next = head.next;
head.next = prev;
return reverseList(next, head);
};
- 먼저 next라는 변수의 현재 head가 가리키고 있는 다음 노드인 head.next를 담는다.
- head.next는 현재 가리키고 있는 다음 노드와의 연결을 끊고, 이전의 노드를 가리킨다.
(처음엔 null을 가리킨다) - 처음의 head.next가 담긴 next는 head가 되고, head는 prev가 되면서 위의 과정을 순환한다.
위와 같은 과정으로 계속 순환하게 되는데, 결국 끝에가면 head는 null 값에 다다를 것이다.
그때는 prev를 반환해주면서 끝이나게 된다.