LC24. Swap Nodes in Pairs

https://leetcode.com/problems/swap-nodes-in-pairs/

  • 링크드 리스트, 방금 푼 문제를 교훈삼아 Two-Point를 전진시켰다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode vroot(0);
        vroot.next=head;
        
        for(auto cur = head, prev = &vroot; cur && cur->next ; cur=cur->next, prev=prev->next->next) {
            ListNode* odd = cur;
            ListNode* even = cur->next;
            
            odd->next = even->next;
            prev->next = even;
            even->next = odd;
        }
        return vroot.next;
    }
};