-
Notifications
You must be signed in to change notification settings - Fork 0
/
SplitLinkedList.cpp
106 lines (98 loc) · 2.62 KB
/
SplitLinkedList.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
#include<bits/stdc++.h>
using namespace std;
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) {}
};
int countNodes(ListNode* &head){
ListNode* temp = head;
int cnt = 0;
while(temp){
temp = temp->next;
cnt++;
}
return cnt;
}
// * BETTER THAN ONLY 13% solutions (BY CREATING NEW NODES)
vector<ListNode*> splitListToParts(ListNode* head, int k) {
int n = countNodes(head);
int parts = k;
int mod = n % k;
vector<ListNode*> ans;
ListNode* ptr = head;
while(ptr and mod--){ // * STARTING N%K NODES
int num = (n / k) + 1;
ListNode *temp = NULL, *head2 = NULL;
while(ptr and num--){ // * ADD N/K + 1 Nodes
ListNode* newNode = new ListNode(ptr->val);
if(temp == NULL){
temp = newNode;
head2 = temp;
}
else{
temp->next = newNode;
temp = temp->next;
}
ptr = ptr->next;
}
parts--;
ans.push_back(head2);
}
while(ptr and parts){
int num = (n / k);
ListNode *temp = NULL, *head2 = NULL;
while(ptr and num--){ // * ADD N/K + 1 Nodes
ListNode* newNode = new ListNode(ptr->val);
if(temp == NULL){
temp = newNode;
head2 = temp;
}
else{
temp->next = newNode;
temp = temp->next;
}
ptr = ptr->next;
}
parts--;
ans.push_back(head2);
}
while(parts--) ans.push_back(NULL);
return ans;
}
// * BETTER THAN 25% solutions (in top) (without creating NEW NODES)
vector<ListNode*> splitListToParts(ListNode* head, int k) {
int n = countNodes(head);
int parts = k;
int mod = n % k;
vector<ListNode*> ans;
ListNode* ptr = head;
while(ptr and mod--){ // * STARTING N%K NODES
int num = (n / k) + 1;
ListNode *prev = NULL, *head2 = ptr;
while(ptr and num--){ // * ADD N/K + 1 Nodes
prev = ptr;
ptr = ptr->next;
}
parts--;
prev->next = NULL; // * CUT THE current LINKED LIST
ans.push_back(head2); // * And push it
}
while(ptr and parts){ // *
int num = (n / k);
ListNode *prev = NULL, *head2 = ptr;
while(ptr and num--){ // * ADD N/K + 1 Nodes
if(head2 == NULL)
head2 = ptr;
prev = ptr;
ptr = ptr->next;
}
prev->next = NULL; // * CUT THE current LINKED LIST
ans.push_back(head2); // * And push it
parts--;
}
while(parts--) ans.push_back(NULL);
return ans;
}