Created
November 9, 2017 21:14
-
-
Save jianminchen/64a17200e4f71739d79ef2a9315d49e5 to your computer and use it in GitHub Desktop.
Linked list splits into small linked list, every two of them length difference at most 1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<ListNode> SplitToMutipleLinkedListGivenValue(ListNode root, int number) | |
{ | |
if(root == null || number < 1) | |
{ | |
return new ArrayList(); | |
} | |
// base case | |
if( number == 1) | |
return root; | |
int length = getLength(root); | |
int smallListLength = length / number; | |
int reside = length % number; | |
List<ListNode> smallLists = new List<ListNode>(); | |
int index = 0; | |
Node rootNode = root; | |
Node current = root; | |
Node previous = null; | |
while(index < number) | |
{ | |
// index == 0 first list | |
int currentLength = (index < residue)? (smallListLength + 1) : smallListLength ; | |
// go over the current list | |
List current = null, previous = null; | |
int indexSmall = 0 ; | |
while(indexSmall < currentLength ) // 0 < 2 | |
{ | |
previous = current;//2 | |
current = current.Next; //3 | |
indexSmall ++; //2 | |
} | |
// add the output | |
previous.Next = null; | |
smallList.Add(rootNode); | |
// | |
rootNode = current; | |
previous = null; | |
index ++; | |
} | |
return smallLists ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment