Problem Solving/Leet Code
1721 Swapping Nodes in a Linked List
딥땔감
2021. 2. 1. 02:42
링크드 리스트에서 두 개의 노드를 교체하는 것을 구현하는 문제이다.
리스트의 앞에서 k번째, 뒤에서 k번째의 노드를 교체해야 하는데, 리스트의 맨 앞에서부터
리스트를 순회하면서 앞에서 k번째, 뒤에서 k번째 노드의 포인터를 저장하고, 각 포인터에 저장된 값을
교환하는 식으로 구현하였다.
C++
더보기
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode* target1, *target2, *temp;
temp = head;
while(k > 0){
target1 = temp;
temp = temp -> next;
--k;
}
target2 = head;
while(temp != nullptr){
temp = temp -> next;
target2 = target2 -> next;
}
swap(target1 -> val, target2 -> val);
return head;
}
};
Python
더보기
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
temp = head
while k > 0:
target1 = temp
temp = temp.next
k -= 1
target2 = head
while temp != None:
temp = temp.next
target2 = target2.next
target1.val, target2.val = target2.val, target1.val
return head
728x90