[JS] Reverse Linked List

2022. 7. 30. 14:00

🔒 문제 (LeetCode 206)

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

Constraints:

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

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

 

🌊 입출력

Example 1:

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

Example 2:

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

Example 3:

Input: head = []
Output: []

 


 

🔑 해결

🌌 알고리즘

1) iterative

ES6 solution : [cur.next, prev, cur] = [prev, cur, cur.next] 가 순서대로 할당되는 것이 아닌 동시에 수행됨. 즉, [cur.next, prev, cur] 의 값이 저장되고 그 값을 가지고 [prev, cur, cur.next] 를 수행하기 때문에 [cur.next] = [prev] 로 값이 변했지만 [cur] = [cur.next] 에는 영향을 끼치지 않음.

/**
 * 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) {
    let [prev, cur] = [null, head];
    while(cur) {
        [cur.next, prev, cur] = [prev, cur, cur.next];
    }
    
    return prev;
};

위의 해결을 풀어 쓴다면 아래와 같음

/**
 * 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) {
    let prev = null;
    let cur = head;
    let next = null;
    
    while(cur) {
        next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
    }
    
    return prev;
};

 

2) recursive

/**
 * 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) {
   function reverse(head, newHead) {
       if(!head) return newHead;
       
       const next = head.next;
       head.next = newHead;
       return reverse(next, head);
    }
    
    return reverse(head, null);
};

'코딩테스트 (JS) > ETC' 카테고리의 다른 글

[JS] Number of 1 Bits  (0) 2022.08.02
[JS] Power of Two  (0) 2022.08.02
[JS] Merge Two Sorted Lists  (0) 2022.07.30
[JS] 디스크 컨트롤러  (0) 2022.07.17
[JS] 다단계 칫솔 판매  (0) 2022.07.05

+ Recent posts