Created
November 8, 2017 08:27
-
-
Save jianminchen/8d2e0efa5510adcc35cbd6f5907900ec to your computer and use it in GitHub Desktop.
Linked list - split in small ones - the peer's code, I will give a code review
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
class ListNode // Node | |
{ | |
int value; | |
public ListNode next; | |
public ListNode(int value) | |
{ | |
this.value = value; | |
} | |
} | |
class LinkedListSplitter | |
{ | |
// SplitMultipleListWithLengthDiffSmallerThanOneGivenListNumber - | |
// Split multiple lists with length difference smaller than one, given the total list number | |
// 1->2, 3 4 | |
public static List<ListNode> split(ListNode head, int k)// head 1->2->3->4, k = 3.// 1->2 3 4, given k > 0, get first list, solve the subproblem k - 1, start from the first node, length%k == 0? the length of list.Length / k : the length of list.Length / k + 1, | |
{ | |
if(head == null || k < 1) | |
return new ArrayList(); | |
if( k < 1) | |
return new ArrayList(); | |
// base case: what if given k conflicts with the linked list length - edge case k > length, 1, 0 | |
// what is the list length value? explicit defined -> | |
// more simple one -> | |
int index = 0; | |
List<ListNode> splittedNodes = new ArrayList(); | |
ListNode next =null; | |
while(head != null) | |
{ | |
next = head.next; //2, 3, 4 , null | |
boolean isOccupiedInIndex = splittedNodes.size() > index; //0 > 0 false, 1 > 1 false, 3 > 0 | |
if( isOccupiedInIndex ) | |
{ | |
ListNode indexNode = splittedNodes.get(index); // get() | |
indexNode.next = head; // 1.next = 4 | |
} | |
else | |
splittedNodes.add(head); // add 1, 2, 3 | |
head.next = null; // 1.next = null, 2.next = null, head.next = null | |
index++; // 1, 2, 3 | |
index = index % k;// 1, 2, 0 | |
head = next; // 2, 3, 4 | |
} | |
return splittedNodes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment