-
Notifications
You must be signed in to change notification settings - Fork 0
/
odd_even_linked_list.cpp
95 lines (79 loc) · 1.86 KB
/
odd_even_linked_list.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
// https://leetcode.com/problems/odd-even-linked-list/
// May 04, 2016
#include <iostream>
#include <vector>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x): val(x), next(NULL) {}
};
class Solution {
public:
ListNode* oddEvenList(ListNode* head)
{
if ((head == NULL) || (head->next == NULL))
{
return head;
}
ListNode* headEvenList = head->next;
ListNode* oddListNode = head;
ListNode* evenListNode = head->next;
while (evenListNode && evenListNode->next)
{
oddListNode->next = evenListNode->next;
oddListNode = oddListNode->next;
evenListNode->next = oddListNode->next;
evenListNode = evenListNode->next;
}
oddListNode->next = headEvenList;
return head;
}
};
ListNode* create_linked_list(vector<int>& vec)
{
if (vec.empty())
{
return NULL;
}
ListNode* head = new ListNode(vec[0]);
ListNode* prevNode = head;
for (vector<int>::iterator it = vec.begin()+1; it != vec.end(); ++it)
{
ListNode* curNode = new ListNode(*it);
prevNode->next = curNode;
prevNode = curNode;
}
return head;
}
void print_linkedlist(ListNode* head)
{
if (head == NULL)
{
return;
}
ListNode* node = head;
while (node)
{
cout << node->val << " ";
node = node->next;
}
}
int main(int argc, char* argv[])
{
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
ListNode* head = create_linked_list(vec);
cout << "initial list: ";
print_linkedlist(head);
Solution sln;
ListNode* headOddEven = sln.oddEvenList(head);
cout << "\nodd even list: ";
print_linkedlist(headOddEven);
return 0;
}