24. Swap Nodes in Pairs

늘보·2021년 7월 9일
0

LeetCode

목록 보기
4/69

💡 풀이

function ListNode(val, next) {
  this.val = val === undefined ? 0 : val;
  this.next = next === undefined ? null : next;
}

// Iterative Solution
var swapPairs = function (head) {
  let dummy = new ListNode(); // dummy data
  dummy.next = head;
  let prev = dummy;

  while (head && head.next) {
    // Declare
    let n1 = head; // 1
    let n2 = head.next; // pointer

    // Swap
    prev.next = n2; // Dummy data의 pointer를 n2로 만들어준다.
    n1.next = n2.next; // n1의 pointer를 n2의 pointer로 만들어준다.
    n2.next = n1; // n2가 가리키는 pointer는 n1(1)이 된다.

    // Assign
    prev = n1; // dummy data를 n1으로 만들어주고
    head = n1.next; // n1이 바라보는 pointer가 head가 된다.
  }

  return dummy.next;
};

// Recursive Solution
var swapPairs = function (head) {
  if (!head || !head.next) return head;
  var v1 = head,
    v2 = head.next,
    v3 = v2.next;
  v2.next = v1;
  v1.next = swapPairs(v3);
  return v2;
};

📝 정리

어제에 이어 두 번째 Linked List 문제였다. Swap에 대한 이해가 부족해 이번 문제도 Discussion과 스터디원들의 도움으로 이해했다. 매일 스터디하면서 푸는 문제들 말고 따로 스스로 Linked List문제를 몇 가지 더 풀어봐야 할 것 같음.

문제 링크
https://leetcode.com/problems/swap-nodes-in-pairs/

LeetCode GitHub
https://github.com/tTab1204/LeetCode/tree/main/%EC%A3%BC%EC%98%81

0개의 댓글