본문 바로가기
LeetCode

[LeetCode] 24. Swap Nodes in Pairs

by JungSeung 2023. 10. 26.
728x90

https://leetcode.com/

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:

출처 : https://leetcode.com/problems/swap-nodes-in-pairs/

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

 

Example 2:

Input: head = []
Output: []

 

Example 3:

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

 

Constraints:

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

 

Code :

var swapPairs = function(head) {
    // 만약 헤드가 null이면 head 반환
    if (head == null) return head;
    // 만약 헤드의 다음 노드가 null이면 head 반환
    if (head.next == null) return head;
    // 두 노드를 스왑하기 위해 임시 변수 temp에 head의 다음 노드 할당
    let temp = head.next;
    // head의 다음 노드를 temp의 다음 노드로 설정
    head.next = temp.next;
    // temp의 다음 노드를 head로 설정하여 노드를 스왑
    temp.next = head;
    // head의 다음 노드를 스왑된 다음 노드에 대해 재귀 호출하여 연결 리스트의 나머지 부분도 스왑
    head.next = swapPairs(head.next);
    // 스왑된 헤드 노드 반환
    return temp;
};

 

Solutions Code :

var swapPairs = function(head) {
    // 만약 head가 존재하지 않거나 head의 다음 노드가 존재하지 않으면 head 반환
    if (!head || !head.next) {
        return head;
    }
    
    // newHead 변수에 head의 다음 노드 할당
    var newHead = head.next;
    // 이전 노드를 나타내는 prev 변수와 현재 노드를 나타내는 curr 변수 초기화
    var prev = null;
    var curr = head;
    
    // curr가 존재하고 curr의 다음 노드가 존재하는 동안 반복
    while (curr && curr.next) {
        // 다음 노드를 나타내는 next 변수 할당
        var next = curr.next;
        // curr의 다음 노드를 next의 다음 노드로 설정
        curr.next = next.next;
        // next의 다음 노드를 curr로 설정하여 노드를 스왑
        next.next = curr;
        
        // prev가 존재하는 경우 prev의 다음 노드를 next로 설정하여 이전 노드와 스왑된 노드 연결
        if (prev) {
            prev.next = next;
        }
        
        // prev 변수에 curr, curr 변수에 curr의 다음 노드로 설정하여 다음 노드로 이동
        prev = curr;
        curr = curr.next;
    }
    
    // 스왑된 헤드 노드 반환
    return newHead;
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90