>> 문제설명
leetcode.com/problems/swapping-nodes-in-a-linked-list/
Swapping Nodes in a Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
정말 single linked list에서 2개의 node를 swap하려고 하다가 결국 숫자만 바꾸기로 했다.
객체를 swap하는건 무척 어렵지만 그냥 숫자만 바꾸는건 간단하다.
이대로 통과가 되는걸 보니 문제에서도 이걸 의도한 듯 하다..
Solution
/**
* 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 swapNodes(ListNode head, int k) {
ArrayList<ListNode> nodeList = new ArrayList<>();
ListNode next = head;
while(next != null){
nodeList.add(next);
next = next.next;
}
int tmp = nodeList.get(k-1).val;
nodeList.get(k-1).val = nodeList.get(nodeList.size()-k).val;
nodeList.get(nodeList.size()-k).val = tmp;
return head;
}
}
728x90
반응형
'Algorithms > LeetCode DailyChallenge' 카테고리의 다른 글
[LeetCode] 376. Wiggle Subsequence / JAVA (0) | 2021.03.18 |
---|---|
[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee / JAVA (0) | 2021.03.16 |
[LeetCode] 322. Coin Change / JAVA (0) | 2021.03.12 |
[LeetCode] 12. Integer to Roman / JAVA (0) | 2021.03.10 |
[LeetCode] 1332. Remove Palindromic Subsequences (0) | 2021.03.08 |