Skip to content

Commit

Permalink
SLList
Browse files Browse the repository at this point in the history
  • Loading branch information
joshHug committed Aug 16, 2016
1 parent d26d5ca commit a62c615
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 0 deletions.
44 changes: 44 additions & 0 deletions lists2/live/IntList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
public class IntList {
public int first;
public IntList rest;

public IntList(int f, IntList r) {
first = f;
rest = r;
}

/** Return the size of the list using... recursion! */
public int size() {
if (rest == null) {
return 1;
}
return 1 + this.rest.size();
}

/** Return the size of the list using no recursion! */
public int iterativeSize() {
IntList p = this;
int totalSize = 0;
while (p != null) {
totalSize += 1;
p = p.rest;
}
return totalSize;
}

/** Returns the ith item of this IntList. */
public int get(int i) {
if (i == 0) {
return first;
}
return rest.get(i - 1);
}

public static void main(String[] args) {
IntList L = new IntList(15, null);
L = new IntList(10, L);
L = new IntList(5, L);

System.out.println(L.get(100));
}
}
Empty file added lists2/live/IntNode.java
Empty file.
66 changes: 66 additions & 0 deletions lists2/live/SLList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/** An SLList is a list of integers, which hides the terrible truth
* of the nakedness within. */
public class SLList {
private static class IntNode {
public int item;
public IntNode next;

public IntNode(int i, IntNode n) {
item = i;
next = n;
}
}

/* The first item (if it exists) is at sentinel.next. */
private IntNode sentinel;
private int size;

/** Creates an empty SLList. */
public SLList() {
sentinel = new IntNode(63, null);
size = 0;
}

public SLList(int x) {
sentinel = new IntNode(63, null);
sentinel.next = new IntNode(x, null);
size = 1;
}

/** Adds x to the front of the list. */
public void addFirst(int x) {
sentinel.next = new IntNode(x, sentinel.next);
size = size + 1;
}

/** Returns the first item in the list. */
public int getFirst() {
return sentinel.next.item;
}

/** Adds x to the end of the list. */
public void addLast(int x) {
size = size + 1;

IntNode p = sentinel;

/* Advance p to the end of the list. */
while (p.next != null) {
p = p.next;
}

p.next = new IntNode(x, null);
}

/** Returns the size of the list. */
public int size() {
return size;
}

public static void main(String[] args) {
/* Creates a list of one integer, namely 10 */
SLList L = new SLList();
L.addLast(20);
System.out.println(L.size());
}
}

0 comments on commit a62c615

Please sign in to comment.