Skip to content

Commit 0814fbd

Browse files
authored
Create 0024-swap-nodes-in-pairs.cpp
1 parent f8ac8e4 commit 0814fbd

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Diff for: cpp/0024-swap-nodes-in-pairs.cpp

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Given a linked list, swap every two adjacent nodes and return its head.
3+
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
4+
5+
Ex. Input: head = [1,2,3,4]
6+
Output: [2,1,4,3]
7+
8+
Time : O(N);
9+
Space : O(1);
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* struct ListNode {
15+
* int val;
16+
* ListNode *next;
17+
* ListNode() : val(0), next(nullptr) {}
18+
* ListNode(int x) : val(x), next(nullptr) {}
19+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
20+
* };
21+
*/
22+
class Solution {
23+
public:
24+
ListNode* swapPairs(ListNode* head) {
25+
if (!head || !head->next)
26+
return head;
27+
28+
ListNode *new_head = head->next;
29+
ListNode *prev = NULL;
30+
31+
while (head && head->next) {
32+
ListNode *next_pair = head->next->next;
33+
ListNode *second = head->next;
34+
35+
if (prev)
36+
prev->next = second;
37+
38+
second->next = head;
39+
head->next = next_pair;
40+
41+
prev = head;
42+
head = next_pair;
43+
}
44+
return new_head;
45+
}
46+
};

0 commit comments

Comments
 (0)