Skip to content

Instantly share code, notes, and snippets.

@quinnzipse
Created November 11, 2019 05:51
Show Gist options
  • Save quinnzipse/bd8243c831f67d713cd217017262fcc6 to your computer and use it in GitHub Desktop.
Save quinnzipse/bd8243c831f67d713cd217017262fcc6 to your computer and use it in GitHub Desktop.
// File Name: NumberList.java
//
// Author: Quinn Zipse
//
// Uses inner classes to try and hide the list data structure from the public
//
public class NumberList {
private NumberNode head;
private NumberList(NumberNode head){
this.head = head;
}
public int get(int index){
if(index < size()) {
NumberNode temp = head;
for (int i = 0; i < index; i++) {
temp = temp.getNext();
}
return temp.getNum();
} else {
throw new IndexOutOfBoundsException();
}
}
@Override
public String toString() {
NumberNode temp = head;
StringBuilder result = new StringBuilder("{");
for(int i=0; i<this.size(); i++){
if(i>0){
result.append(", ");
}
result.append(temp.getNum());
temp = temp.getNext();
}
result.append("}");
return result.toString();
}
public void add(int index, int num){
if(index < size()+1){
NumberNode pos = head;
for(int i=1; i<index; i++){
pos = pos.getNext();
}
NumberNode temp = new NumberNode(num, pos.getNext());
pos.setNext(temp);
} else {
throw new IndexOutOfBoundsException();
}
}
public void remove(int index){
if(index < size()){
NumberNode pos = head;
for(int i=1; i<index; i++){
pos = pos.getNext();
}
pos.setNext(pos.getNext().getNext());
} else {
throw new IndexOutOfBoundsException();
}
}
public NumberList newReverse(){
NumberNode prev = null, temp;
for(NumberNode pos = head; pos!= null; pos = pos.getNext()){
temp = new NumberNode(pos.getNum(), prev);
prev = temp;
}
return new NumberList(prev);
}
public void reverse(){
NumberNode pos, next, prev=null;
for(pos = head; pos!=null; pos = next){
next = pos.getNext();
pos.setNext(prev);
prev = pos;
}
head = prev;
}
public int size(){
int i=0;
for(NumberNode pos = head; pos!= null; pos = pos.getNext()){
i++;
}
return i;
}
private static 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 main(String[] args) {
NumberList list = new NumberList(new NumberNode(2, new NumberNode(3, new NumberNode(4))));
System.out.println(list.toString());
System.out.println(list.newReverse().toString());
list.reverse();
System.out.println(list.toString());
System.out.println(list.get(1));
list.add(1, 100);
System.out.println(list.toString());
list.remove(1);
System.out.println(list.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment