runtime 0 ms, beats 100% of cpp submissions
O(n) solution with explanation

tags: linked list, pointer

Swap Nodes in Pairs

๐Ÿ“– description

็ตฆๅฎšไธ€ๅ€‹ linked list ๏ผŒๅฐ‡็›ธ้„ฐ็š„ๅ…ฉๅ€‹้ปž็ฟป่ฝ‰ใ€‚

ex.
    1 -> 2 -> 3 -> 4

    2 -> 1 -> 4 -> 3

    1ใ€2ไบ’ๆ›๏ผŒ3ใ€4ไบ’ๆ›

๐Ÿง  solution

ๆ นๆ“š้กŒๆ„ๆจกๆ“ฌๅณๅฏ๏ผŒไฝฟ็”จๅ…ฉๅ€‹ pointer ๅˆ†ๅˆฅๆŒ‡ๅ‘้œ€่ฆไบ’ๆ›็š„ๅ…ฉๅ€‹้ปž๏ผŒไบ’ๆ›ๅฎŒๅพŒๅ†ๅ‘ๅพŒ็งปๅ‹•ๅ…ฉๆ ผใ€‚

โณ time complexity

้ๆญทไธ€ๆฌก list ๏ผŒๆ™‚้–“่ค‡้›œๅบฆ O(n)
็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(n)

๐Ÿ“ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==nullptr || head->next==nullptr){ // ็ขบไฟๆœ‰่‡ณๅฐ‘ๅ…ฉๅ€‹้ปž
return head;
}
ListNode* f = head; // first pointer
ListNode* s = head->next; // second pointer
ListNode* ans = f;
while(s!=nullptr){
swap(f->val,s->val); // ไบคๆ›ๆ•ธๅ€ผ
f=s->next;
if(f==nullptr) break;
s=s->next->next;
}
return ans;
}
};