MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / splitListToParts

Method splitListToParts

SplitLinkedListInParts.java:12–43  ·  view source on GitHub ↗
(ListNode head, int k)

Source from the content-addressed store, hash-verified

10 */
11class Solution {
12 public ListNode[] splitListToParts(ListNode head, int k) {
13 //find size
14 ListNode temp = head;
15 int size=0;
16 while(temp!=null){
17 size++;
18 temp = temp.next;
19 }
20 ListNode res[] = new ListNode[k];
21 temp = head;
22 int avg = size/k;
23 int extra = size%k;
24 for(int i=0;i<k;i++){
25 if(temp==null) break;
26 ListNode curHead = temp;
27 ListNode prev = null;
28 int len=0;
29 while(temp!=null && len<avg){
30 prev = temp;
31 temp = temp.next;
32 len++;
33 }
34 if(extra>0){
35 prev = temp;
36 temp = temp.next;
37 extra--;
38 }
39 prev.next = null; //detach previous list
40 res[i] = curHead; //insert head
41 }
42 return res;
43 }
44}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected