알고리즘/leetcode
[Java] leetcode 1721. Swapping Nodes in a Linked List
24시간이모자란
2023. 5. 16. 00:10
문제
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/description/
Swapping Nodes in a Linked List - LeetCode
Can you solve this real interview question? Swapping Nodes in a Linked List - You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from t
leetcode.com
알아야 할 개념
- 포인터 이동
풀이
풀이 알고리즘은 다음과 같다.
- k 번째 만큼 첫 번째 포인터 이동.
- 첫 번째 포인터의 next 가 null이 될때까지 두 번째 포인터 이동
- first second 포인터 교환
- 정답을 리턴한다.
코드
class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode first, second, temp ;
int val;
first = head;
second = head;
while(k--> 1){ // k 번째 만큼 첫 번째 포인터 이동.
first = first.next;
}
temp = first;
while(temp.next != null){//첫 번째 포인터의 next 가 null이 될때까지 두 번째 포인터 이동
second = second.next;
temp = temp.next;
}
//swap first second 포인터 교환
val = first.val;
first.val = second.val;
second.val = val;
return head;
}
}