forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
136 lines (100 loc) · 2.77 KB
/
main2.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/// Source : https://leetcode.com/problems/split-linked-list-in-parts/description/
/// Author : liuyubobobo
/// Time : 2017-11-12
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Create New Lists
/// Time Complexity: O(len(list))
/// Space Complexity: O(1)
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* root, int k) {
int length = getLength(root);
int average_size = length / k;
int left = length % k;
vector<ListNode*> res;
for(int i = 0 ; i < k ; i ++){
int sz = average_size + (i < left ? 1 : 0);
if(sz == 0)
res.push_back(NULL);
else{
ListNode* dummyRoot = new ListNode(-1);
ListNode* cur = dummyRoot;
for(int i = 0 ; i < sz ; i ++){
cur->next = new ListNode(root->val);
cur = cur->next;
root = root->next;
}
res.push_back(dummyRoot->next);
dummyRoot->next = NULL;
delete dummyRoot;
}
}
return res;
}
private:
int getLength(ListNode* node){
int cnt = 0;
while(node != NULL){
cnt ++;
node = node->next;
}
return cnt;
}
};
/// LinkedList Test Helper Functions
ListNode* createLinkedList(int arr[], int n){
if( n == 0 )
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for( int i = 1 ; i < n ; i ++ ){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
void printLinkedList(ListNode* head){
ListNode* curNode = head;
while( curNode != NULL ){
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout<<"NULL"<<endl;
return;
}
void deleteLinkedList(ListNode* head){
ListNode* curNode = head;
while( curNode != NULL ){
ListNode* delNode = curNode;
curNode = curNode->next;
delete delNode;
}
return;
}
int main() {
int nums1[3] = {1, 2, 3};
ListNode* root1 = createLinkedList(nums1, 3);
int k1 = 5;
vector<ListNode*> res1 = Solution().splitListToParts(root1, k1);
for(ListNode* node: res1)
printLinkedList(node);
cout << endl;
// ---
int nums2[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ListNode* root2 = createLinkedList(nums2, 10);
int k2 = 3;
vector<ListNode*> res2 = Solution().splitListToParts(root2, k2);
for(ListNode* node: res2)
printLinkedList(node);
cout << endl;
return 0;
}