[LeetCode/24/Java]Swap Nodes in Pairs
풀이
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if((head == null) || (head.next == null)) return head;
ListNode result = new ListNode(-1, head);
ListNode prev = result;
while(prev.next != null && prev.next.next != null) {
int temp = prev.next.val;
prev.next.val = prev.next.next.val;
prev.next.next.val = temp;
prev = prev.next.next;
}
return result.next;
}
}
후기
LinkedList의 개념을 이해하면 풀 수 있는 문제였습니다.
반복문을 돌면서 앞뒤 값을 변환시켜줍니다.
time complexity O(N)
space complexity O(N)
728x90
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/70/Java]Climbing Stairs (0) | 2022.05.29 |
---|---|
[LeetCode/119/Java]Pascal's Triangle II (0) | 2022.05.29 |
[LeetCode/700/Java]Search in a Binary Search Tree (0) | 2022.05.28 |
[LeetCode/206/Java]Reverse Linked List (0) | 2022.05.28 |
[LeetCode/344/Java]Reverse String (0) | 2022.05.28 |