Last active
October 21, 2020 23:12
-
-
Save sophieKaelin/51ecd5bb844d822f619739cbedf1f14b to your computer and use it in GitHub Desktop.
COMP1010 Week 11 Recursive Data Structure - SubList Method
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 Node subList(Node start, int idx1, int idx2) { | |
int length = getLength(start, 0); //how many items | |
if(!isValidIdx(length, idx1, idx2) || start == null) { | |
return null; | |
} | |
Node temp = get(new Node(start.data, start.next), idx1); //get item at index | |
return subList(temp, (idx2-idx1+1)); | |
} | |
/*** | |
* | |
* @param start | |
* @param numItems | |
* @return a linked list with "numItems" amount of items | |
*/ | |
public static Node subList(Node start, int numItems) { | |
if(numItems <= 0) { //end of list | |
return null; | |
} | |
Node temp = new Node(start.data); //create new item | |
temp.next = subList(start.next, numItems -1); //get the next item | |
return temp; //once done, return that first node back to the caller function | |
} | |
/*** | |
* | |
* @param head - first node in the list | |
* @param length - counter for how many items there are | |
* @return the number of items in the linked list | |
*/ | |
public static int getLength(Node head, int length) { | |
if(head != null) { | |
return getLength(head.next, length+1); | |
} | |
return length; | |
} | |
/*** | |
* | |
* @param l - number of items in the list | |
* @param idx1 | |
* @param idx2 | |
* @return if the range provided by idx1 and idx2 is valid for a list of size l | |
*/ | |
public static boolean isValidIdx(int l, int idx1, int idx2) { | |
return idx1 >= 0 && idx1 <= idx2 && idx2 < l; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment