Created
November 8, 2017 08:25
-
-
Save jianminchen/9847cd7bf78e45a87de29f03cccba5b5 to your computer and use it in GitHub Desktop.
Linked list - split into small ones - recursive solution - need to work on the code to make it compile and run with test case later.
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
public static IList<Node> SplitToMutipleLinkedListGivenValue(Node root, int number )// 1->2->3->4 3 1->2,3,4 | |
{ | |
if(root == null || number < 1)// | |
{ | |
return new List<Node>(); | |
} | |
if(number == 1)// | |
{ | |
return root; | |
} | |
int length = GetLength(root); // 4//10*10 times | |
// 2, give 4, talk length 1, 1, 0, 0, | |
IList<Node> lists = new List<Node>(); // | |
int smallLength = length / number; //1 | |
int firstListLength = (length % number == 0)? smallLength : (smallLength + 1); //2 | |
// travel to the list, and find the last node in the first list, to mark its next = null , get next node as root, recursive call | |
int index = 0; | |
Node current = root; | |
Node previous = null; | |
while(index < firstListLength) // 0 < 2 | |
{ | |
previous = current;//2 | |
current = current.Next; //3 | |
index ++; //2 | |
} | |
// previous is last node in the list | |
previous.next = null; 1,2 | |
lists.Add(root); 1,2 | |
lists.AddRange(SplitToMutipleLinkedListGivenValue(current, number - 1); //3 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment