728x90
반응형
문제
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 changed.)
내 생각
인접한 두 노드를 swap하는 문제이다.
두번째 노드(head.next)의 다음 노드에 head 를 붙이고(swap), 두번째로 넘어간 기존 head의 next에 재귀호출한 세번째 노드를 붙여 준뒤 새로운 head인 두번째노드를 반환해준다.
그러니까 .next로 다음 노드를 가리키면 그 다음 노드 뒤(.next)를 다시 첫 노드로 설정하면 됨!
내 코드
/**
* 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) {
//빈 리스트거나 노드가 하나만 있는 경우 그대로 return
if (head==null || head.next==null) return head;
//교환 할 노드
ListNode second = head.next;
ListNode third = second.next;
//두 번째 노드 <-> 첫 번째 노드
second.next = head;
//세 번째 노드 <-> 그 이후 노드(재귀)
head.next = swapPairs(third);
//새로운 헤드 return (두 노드씩 쌍으로 교환된 연결리스트 return)
return second;
}
}
728x90
반응형
'Algorithm > 코딩테스트 (Java)' 카테고리의 다른 글
[LeetCode] 148. Sort List (0) | 2024.05.27 |
---|---|
[LeetCode] 424. Longest Repeating Character Replacement (0) | 2024.05.24 |
[LeetCode] 300. Longest Increasing Subsequence (0) | 2024.05.20 |
[LeetCode] 36. Valid Sudoku (0) | 2024.05.13 |
[LeetCode] 79. Word Search (0) | 2024.05.08 |
댓글