본문 바로가기
Problem Solving/LeetCode

[LeetCode] 24. Swap Nodes in Pairs - Java

by graycode 2026. 5. 17.

 문제 링크

 

Swap Nodes in Pairs - LeetCode

Can you solve this real interview question? 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 chan

leetcode.com

 

 풀이 코드

public class Solution {

    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1), cur = dummy;
        cur.next = head;
        while (cur.next != null && cur.next.next != null) {
            ListNode a = cur.next, b = cur.next.next;
            a.next = b.next;
            b.next = a;
            cur.next = b;
            cur = cur.next.next;
        }

        return dummy.next;
    }

}

댓글