본문 바로가기

알고리즘/LeetCode

[LeetCode/24/Java]Swap Nodes in Pairs

[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
반응형