Skip to content

Instantly share code, notes, and snippets.

View gaurav1780's full-sized avatar

Gaurav Gupta gaurav1780

  • Macquarie University
  • Sydney
View GitHub Profile

Workshop Solutions - Custom-built linked list

This workshop assumes the following class definitions:

  1. Node.java
  2. MyLinkedList.java (this is the class to which we'll add instance methods)

Question 1

Add an instance method getFirstItem in class MyLinkedList that returns the data value held in the first node (if any). Return null if there is nothing in the list.

Workshop Solutions - Custom-built array-based list

Array as a contiguous block

Question 1

Consider the following array creation:

int[] data = new int[5000];

Workshop - Custom-built linked list

This workshop assumes the following class definitions:

  1. Node.java
  2. MyLinkedList.java (this is the class to which we'll add instance methods)

Question 1

Add an instance method getFirstItem in class MyLinkedList that returns the first item (if any). Return null if there is nothing in the list.

public class MyLinkedList {
private Node head;
public void addToFront(int item) {
//create a node that has the current head (even if null) as the next node
Node node = new Node(item, head);
//update new head to the added node
head = node;
}
public class Node {
private Node next;
private int data;
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public class MyArrayList {
private int[] data;
private int nItems;
public MyArrayList() {
data = new int[10];
nItems = 0;
}
public int size() {
@gaurav1780
gaurav1780 / CustomBuiltArrayListWorkshop.md
Last active October 12, 2018 22:04
Workshop for custom-built array-based list

Workshop - Custom-built array-based list

Array as a contiguous block

Question 1

Consider the following array creation:

int[] data = new int[5000];
public class Client {
/**
*
* @param arr
* @return the sum of all even numbers
* in the array passed
* for example,
* if arr = {4, 9, -6, 0, -15, 8},
* return 4+(-6)+0+8=6
*/
public static boolean allPositives(int[] arr) {
for(int i=0; i < arr.length; i++) { //(first item is at index 0 not 1)
if(arr[i] <= 0) //check if the current item is NOT positive
return false;
/*
if it IS positve, you cannot return true immediately
as one or more of the subsequent items might not be!
*/
}
//loop ended, means all items checked, none NOT positive
/**
* @param arr: assume it contains at least one item
* @return true if all the items are positve, false otherwise
* Some input-output mappings:
* {10, 70, 20, 90} -> true
* {10, 70, -20, 90} -> false
* {-10, 70, 20, 90} -> false
* {1, 7, 2, -9} -> false
* {4, 0, 9, 6, 8, 3} -> false
* {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} -> true