Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created November 9, 2017 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/64a17200e4f71739d79ef2a9315d49e5 to your computer and use it in GitHub Desktop.
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.
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