-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24.swap-nodes-in-pairs.cpp
91 lines (89 loc) · 1.8 KB
/
24.swap-nodes-in-pairs.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @lc app=leetcode id=24 lang=cpp
*
* [24] Swap Nodes in Pairs
*
* https://leetcode.com/problems/swap-nodes-in-pairs/description/
*
* algorithms
* Medium (57.98%)
* Likes: 6347
* Dislikes: 282
* Total Accepted: 814K
* Total Submissions: 1.4M
* Testcase Example: '[1,2,3,4]'
*
* Given a linked list, swap every two adjacent nodes and return its head. You
* must solve the problem without modifying the values in the list's nodes
* (i.e., only nodes themselves may be changed.)
*
*
* Example 1:
*
*
* Input: head = [1,2,3,4]
* Output: [2,1,4,3]
*
*
* Example 2:
*
*
* Input: head = []
* Output: []
*
*
* Example 3:
*
*
* Input: head = [1]
* Output: [1]
*
*
*
* Constraints:
*
*
* The number of nodes in the list is in the range [0, 100].
* 0 <= Node.val <= 100
*
*
*/
// @lc code=start
/**
* 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) {
ListNode *node = head;
ListNode *previous = nullptr;
while(node != nullptr)
{
if(node->next != nullptr)
{
ListNode *next = node->next;
node->next = next->next;
next->next = node;
if(node == head)
{
head = next;
}
if(previous != nullptr)
{
previous->next = next;
}
}
previous = node;
node = node->next;
}
return head;
}
};
// @lc code=end