forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplit Linked List in Parts.java
40 lines (35 loc) · 995 Bytes
/
Split Linked List in Parts.java
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
class Solution {
public ListNode[] splitListToParts(ListNode head, int k) {
ListNode[] arr=new ListNode[k];
if(k<2 || head==null || head.next==null){
arr[0]=head;
return arr;
}
ListNode temp=head;
int len=1;
while(temp.next!=null){
len++;
temp=temp.next;
}
int partition= len/k; //no of part 3
int extra=len%k; //extra node 1 0
ListNode curr=head;
ListNode prev=null;
int index=0;
while(head!=null){
arr[index++]=curr;
for(int i=0; i<partition && curr!=null ; i++){
prev=curr;
curr=curr.next;
}
if(extra>0){
prev=curr;
curr=curr.next;
extra--;
}
head=curr;
prev.next=null;
}
return arr;
}
}