Skip to content

Instantly share code, notes, and snippets.

@quinnzipse
Created October 30, 2019 04:09
Show Gist options
  • Save quinnzipse/4c85baa1d46c762def97a2f85f77f8ea to your computer and use it in GitHub Desktop.
Save quinnzipse/4c85baa1d46c762def97a2f85f77f8ea to your computer and use it in GitHub Desktop.
Basic Linked list and a few tests. Just a simple assignment for CS220.
public class NumberNode {
private NumberNode next;
private int num;
public NumberNode(int num, NumberNode next) {
this.num = num;
this.next = next;
}
public NumberNode(int num) {
this(num, null);
}
public NumberNode() {
this(0, null);
}
public NumberNode getNext() {
return next;
}
public void setNext(NumberNode next) {
this.next = next;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public static void printList(NumberNode head) {
System.out.print("{");
NumberNode pos = head;
while(pos != null) {
if(head != pos) System.out.print(",");
System.out.print(pos.getNum());
pos = pos.getNext();
}
System.out.println("}");
}
public void insertAfter(int number) {
this.setNext(new NumberNode(number, this.getNext()));
}
public void removeAfter() {
NumberNode temp = this.getNext();
this.setNext(temp.getNext());
temp.setNext(null);
}
public int get(int index) throws Exception {
NumberNode pos = this;
for(int i=0; i<index; i++) {
pos = pos.getNext();
if(pos == null) throw new Exception("Index not in list.");
}
return pos.getNum();
}
public int length() {
NumberNode pos = this;
int i = 0;
while(pos != null) {
i++;
pos = pos.getNext();
}
return i;
}
public static void main(String args[]) {
final NumberNode head = new NumberNode(1, new NumberNode(2, new NumberNode(3)));
System.out.print("Original list: ");
printList(head);
System.out.println("Adding 4 after the head");
head.insertAfter(4);
System.out.print("New list: ");
printList(head);
System.out.println("Removing the 4 I just added");
head.removeAfter();
System.out.print("Updated list: ");
printList(head);
try {
System.out.println("Getting number at index 2: " + head.get(2));
} catch(Exception e) {
System.out.println("There is not an index 2");
}
System.out.println("The length of this linked list is: " + head.length());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment