#include <bits/stdc++.h>
using
namespace
std;
class
Node {
public
:
int
data;
Node* next;
};
int
sizeOfLL(Node* head)
{
int
size = 0;
while
(head != NULL) {
++size;
head = head->next;
}
return
size;
}
vector<Node*> Partition_of_list(Node* head)
{
int
size = sizeOfLL(head);
Node* temp = head;
vector<Node*> ans;
if
(3 >= size) {
while
(temp != NULL) {
Node* next = temp->next;
temp->next = NULL;
ans.push_back(temp);
temp = next;
}
int
y = 3 - size;
while
(y != 0) {
ans.push_back(NULL);
y--;
}
}
else
{
int
minSize = size / 3;
int
rem = size % 3;
while
(size > 0 && temp != NULL) {
int
m = 0;
if
(rem != 0) {
m = minSize + 1;
rem--;
}
else
{
m = minSize;
}
Node* curr = temp;
for
(
int
j = 1; j < m
&& temp->next != NULL;
j++) {
temp = temp->next;
}
if
(temp->next != NULL) {
Node* x = temp->next;
temp->next = NULL;
temp = x;
ans.push_back(curr);
}
else
{
ans.push_back(curr);
break
;
}
size -= m;
}
}
return
ans;
}
void
push(Node** head,
int
d)
{
Node* temp =
new
Node();
temp->data = d;
temp->next = NULL;
if
((*head) == NULL)
(*head) = temp;
else
{
Node* curr = (*head);
while
(curr->next != NULL) {
curr = curr->next;
}
curr->next = temp;
}
}
void
display(Node* head)
{
while
(head->next != NULL) {
cout << head->data <<
"->"
;
head = head->next;
}
cout << head->data <<
"\n"
;
}
int
main()
{
Node* head = NULL;
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
push(&head, 5);
vector<Node*> v = Partition_of_list(head);
for
(
int
i = 0; i < v.size(); i++) {
display(v[i]);
}
return
0;
}
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment