LeetCode Swap Nodes in Pairs (JavaScript)

2025. 11. 19. 17:54·코딩테스트/LeetCode

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

문제 설명

더보기

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

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

Output: [2,1,4,3]

Explanation:

Example 2:

Input: head = []

Output: []

Example 3:

Input: head = [1]

Output: [1]

Example 4:

Input: head = [1,2,3]

Output: [2,1,3]

Constraints:

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

문제 풀이

노드의 연결관계를 다시 세팅하기위해 특정 노드의 prev, next의 값을 유지하는게 중요

3번의 1~4번을 next가 null인 경우, 즉 비교할 대상이 없을 때 까지 반복하여 진행

/**
 * 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 swapPairs = function(head) {
    if (!head) return head;

    let dummy = new ListNode(0, head);

    let prev = dummy;
    let current = head;

    while (current && current.next) {
        const node1 = current;
        const node2 = current.next;
        const node3 = node2.next;

        prev.next = node2;
        node2.next = node1;
        node1.next = node3;

        prev = node1;
        current = node1.next;
    }

    return dummy.next;
};

 


결론

연결 관계에서 swap을 잘 하기 위해 prev, next의 연결 정보를 유지시켜 두는게 핵심

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Next Permutaion (JavaScript), 순열  (0) 2025.11.22
LeetCode Divide Two Integers (JavaScript), 비트 연산  (0) 2025.11.21
LeetCode Word Search (JavaScript), DFS  (0) 2025.11.18
LeetCode Generate Parentheses (JavaScript)  (0) 2025.11.17
LeetCode Remove Nth Node From End of List (JavaScript)  (0) 2025.11.17
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Next Permutaion (JavaScript), 순열
  • LeetCode Divide Two Integers (JavaScript), 비트 연산
  • LeetCode Word Search (JavaScript), DFS
  • LeetCode Generate Parentheses (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (213) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (127) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (38) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Swap Nodes in Pairs (JavaScript)
상단으로

티스토리툴바