File tree Expand file tree Collapse file tree 1 file changed +90
-0
lines changed
LeetCode/Split_Linked_List_in_Parts Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ #include < gtest/gtest.h>
3
+ using namespace std ;
4
+
5
+ // // START
6
+ /*
7
+ ## Split Linked List in Parts
8
+
9
+ */
10
+
11
+ /* *
12
+ * Definition for singly-linked list.
13
+ */
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
+ class Solution {
22
+ public:
23
+ vector<ListNode *> splitListToParts (ListNode *head, int k) {
24
+ int length = 0 ;
25
+ ListNode *tmp = head;
26
+ while (tmp) {
27
+ tmp = tmp->next ;
28
+ length++;
29
+ }
30
+ int n = length / k;
31
+ int remain = length % k;
32
+ if (n == 0 ) {
33
+ n = 1 ;
34
+ remain = 0 ;
35
+ }
36
+
37
+ vector<ListNode *> rets;
38
+ tmp = head;
39
+ int count = 0 ;
40
+ ListNode* last = nullptr ;
41
+ while (tmp) {
42
+ if (count == n + (remain > 0 ? 1 : 0 )) {
43
+ if (!rets.empty ()) {
44
+ last->next = nullptr ;
45
+ }
46
+ remain--;
47
+ rets.push_back (tmp);
48
+ count = 0 ;
49
+ } else {
50
+ if (!rets.empty ()) {
51
+ last->next = tmp;
52
+ } else {
53
+ rets.push_back (tmp);
54
+ }
55
+ }
56
+ count++;
57
+ last = tmp;
58
+ tmp = tmp->next ;
59
+ }
60
+ while (rets.size () < k) {
61
+ rets.push_back ({});
62
+ }
63
+ return rets;
64
+ }
65
+ };
66
+
67
+ // // END
68
+ struct T {};
69
+
70
+ TEST (Solution, test) {
71
+ T ts[] = {
72
+ {
73
+
74
+ },
75
+ {
76
+
77
+ },
78
+
79
+ };
80
+
81
+ for (T t : ts) {
82
+ Solution solution;
83
+ }
84
+ }
85
+
86
+ int main () {
87
+ testing::InitGoogleTest ();
88
+
89
+ return RUN_ALL_TESTS ();
90
+ }
You can’t perform that action at this time.
0 commit comments