๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 206 - Reverse Linked List (Easy)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 206๋ฒˆ

ํ’€์ด ๊ณผ์ •

์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ ์˜ ํฌ์ธํ„ฐ๋ฅผ ๋’ค์ง‘๋Š” ์—ฐ์‚ฐ์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๊ฐ€์žฅ ์ง๊ด€์ ์ธ ๋ฐฉ๋ฒ•์œผ๋กœ ์žฌ๊ท€ ํ˜ธ์ถœ ์„ ์ด์šฉํ•ด์„œ ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.
๊ฐ๊ฐ์˜ ์žฌ๊ท€ ํ˜ธ์ถœ์€ ๋‹ค์Œ ๋…ธ๋“œ๋ถ€ํ„ฐ ๋ ๋…ธ๋“œ๊นŒ์ง€์˜ ๋’ค์ง‘ํžŒ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋Œ€ํ•˜๋ฉฐ
ํ•ด๋‹น ๊ฒฐ๊ณผ๋ฅผ ํ† ๋Œ€๋กœ ํ˜„์žฌ ๋…ธ๋“œ์˜ ํฌ์ธํ„ฐ ๊ฐ’์„ ๋ณ€๊ฒฝํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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 newHead = null;

  function reverse(cur) {
    if (!cur) return null;

    const next = reverse(cur.next);
    if (next) next.next = cur;
    else newHead = cur;

    return cur;
  }

  reverse(head);
  if (head) head.next = null;

  return newHead;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€