-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap_nodes_in_pairs.cpp
105 lines (87 loc) · 2 KB
/
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// https://oj.leetcode.com/problems/swap-nodes-in-pairs/
// Date: Nov 25, 2014
#include <iostream>
#include <vector>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x): val(x), next(NULL) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head)
{
if (head == NULL)
{
return head;
}
ListNode* prevNode = NULL;
ListNode* node1 = head;
while ((node1) && (node1->next))
{
ListNode* node2 = node1->next;
ListNode* nextNode = node2->next;
node1->next = nextNode;
node2->next = node1;
if (prevNode)
{
prevNode->next = node2;
}
else
{
head = node2;
}
// now preparing for next swap of pairs
prevNode = node1;
node1 = node1->next;
}
return head;
}
};
ListNode* create_list(vector<int>& vec)
{
if (vec.size() == 0)
{
return NULL;
}
ListNode* head = new ListNode(vec.front());
ListNode* curNode = head;
for (vector<int>::iterator it = vec.begin()+1; it != vec.end(); ++it)
{
ListNode* nextNode = new ListNode(*it);
curNode->next = nextNode;
curNode = nextNode;
}
return head;
}
void display_list(ListNode* head)
{
if (head == NULL)
{
return;
}
ListNode* curNode = head;
cout << curNode->val;
curNode = curNode->next;
while (curNode)
{
cout << "," << curNode->val;
curNode = curNode->next;
}
}
int main(int argc, char* argv[])
{
int arr[] = {1,2,3};
vector<int> vec(arr, arr+sizeof(arr)/sizeof(arr[0]));
ListNode* head = create_list(vec);
Solution sln;
head = sln.swapPairs(head);
display_list(head);
return 0;
}
/*
Possibility of odd number of nodes:
https://oj.leetcode.com/discuss/2583/there-any-grantee-that-there-will-always-even-number-of-nodes
*/