❒ Description
제목 | Swap Nodes In Pairs |
링크 | https://leetcode.com/problems/swap-nodes-in-pairs/description/ |
자료구조 | 선형 (연결 리스트) |
❒ Solution
1. 값만 교환 : 임시 변수를 사용
public ListNode swapPairs(ListNode head) {
ListNode node = head;
while (node != null && node.next != null) {
int temp;
temp = node.val;
node.val = node.next.val;
node.next.val = temp;
node = node.next.next;
}
return head;
}
2. 재귀 구조로 스왑
public ListNode swapPairs(ListNode head) {
if (head != null && head.next != null) {
ListNode p = head.next;
head.next = swapPairs(head.next.next);
p.next = head;
return p;
}
return head;
}
재귀는 이렇게 그려서 보는게 이해 + 숙련하는데 도움이 되는 것 같음
'Algorithm > 문제풀이' 카테고리의 다른 글
[LeetCode#739] Daily Temperatures (0) | 2024.07.31 |
---|---|
[LeetCode#92] Reverse Linked List II (0) | 2024.07.28 |
[LeetCode#206] Reverse Linked List (0) | 2024.07.28 |
[LeetCode#21] Merge Two Sorted Lists (0) | 2024.07.24 |
[LeetCode#234] Palindrome Linked List (0) | 2024.07.24 |