리트코드/easy
[리트코드] 206. Reverse Linked List - js
bbeyak
2023. 7. 12. 12:48
반응형
1. 문제
https://leetcode.com/problems/reverse-linked-list/
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
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;
};
반응형