공부/알고리즘
LeetCode 24. Swap Nodes in Pairs C++ Solution
토고미
2021. 9. 4. 21:07
/**
* 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* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL){
return head;
}
ListNode* next = head->next;
ListNode* answer = head->next;
head->next = next->next;
next->next = head;
next = head->next;
while(head->next != NULL && next->next != NULL){
next = head->next;
head->next = next->next;
head = head->next;
next->next = head->next;
head->next = next;
head = head->next;
next = head->next;
}
return answer;
}
};
노드만으로 해결