Leetcode

24. Swap Nodes in Pairs

Doromi 2024. 6. 24. 16:52
728x90
반응형

주어진 연결 리스트에서 매 두 노드씩 쌍을 지어서 교환한 후의 연결 리스트를 반환합니다. 노드는 값만 교환하지 않고 실제로 교환합니다.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode SwapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = dummy;
        
        while(current.next != null && current.next.next != null){
            ListNode first = current.next;
            ListNode second = current.next.next;

            first.next = second.next;
            second.next = first;
            current.next = second;

            current = first;
        }

        return dummy.next;
    }
}
예시
  • 입력: head = [1,2,3,4]
  • 출력: [2,1,4,3]
접근 방법
  1. 가상(head) 노드를 만듭니다. (이는 편리하게 첫 번째 노드와 그 앞의 노드를 처리하기 위해 사용)
  2. 현재 노드(current)를 가상 노드로 설정하고, 그 다음 노드와 다다음 노드를 교환합니다.
  3. 이를 현재 노드가 null이거나 다음 노드가 null이 될 때까지 반복합니다.
설명
  1. ListNode 클래스는 연결 리스트의 노드를 정의합니다.
  2. SwapPairs 함수는 주어진 연결 리스트의 노드를 쌍으로 교환합니다.
  3. 가상 노드(dummy)를 사용하여 리스트의 시작 부분을 쉽게 처리할 수 있게 합니다.
  4. while 루프는 리스트의 끝까지 각 두 노드를 쌍으로 교환합니다.
  5. 교환 후 현재 노드를 다음 쌍으로 이동합니다.
728x90
반응형