반응형
1. 문제
https://leetcode.com/problems/reverse-linked-list/
2. 코드
/**
* 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) {
if (head === null) return head; // 리스트가 비었을 경우
let current = head; // [1,2,3,4,5]
let previous = null;
while (current !== null) {
let temp = current.next; // [2,3,4,5] -> [3,4,5]...
current.next = previous; // 노드 연결 순서 뒤집기
previous = current; // [1] -> [2,1] -> [3,2,1]...
current = temp;
}
return previous;
};
반응형
'리트코드 > easy' 카테고리의 다른 글
[리트코드] 136. Single Number - js (0) | 2023.07.19 |
---|---|
[리트코드] 118. Pascal's Triangle - js (0) | 2023.07.18 |
[리트코드] 104. Maximum Depth of Binary Tree - js (0) | 2023.07.11 |
[리트코드] 94. Binary Tree Inorder Traversal - js (0) | 2023.07.10 |
[리트코드] 226. Invert Binary Tree - js (0) | 2023.07.09 |