Skip to content

Instantly share code, notes, and snippets.

@zwilias
Created October 22, 2012 17:25
Show Gist options
  • Save zwilias/3932782 to your computer and use it in GitHub Desktop.
Save zwilias/3932782 to your computer and use it in GitHub Desktop.
add a method set(int n, Object o) which replaces the nth element in the list
public class Assignment {
public static void main(String[] args) {
LinkedList list = new LinkedList();
for(int i = 4; i > 0; i--) {
list.addFirst(i);
}
list.print();
System.out.println("The size is: " + list.size() + ".");
list.set(2, 66);
list.print();
}
}
public class LinkedList {
private class ListElement {
private Object el1;
private ListElement el2;
public ListElement(Object el, ListElement nextElement) {
el1 = el;
el2 = nextElement;
}
public ListElement(Object el) {
this(el,null);
}
public Object first() {
return el1;
}
public ListElement rest() {
return el2;
}
public void setFirst(Object value) {
el1 = value;
}
public void setRest(ListElement value) {
el2 = value;
}
}
private ListElement head;
private int count;
public LinkedList() {
head = null;
}
public void addFirst(Object o) {
head = new ListElement(o,head);
count++;
}
public Object getFirst() {
return head.first();
}
public Object get(int n) {
ListElement d = head;
while(n>0)
{
d = d.rest();
n--;
}
return d.first();
}
public void print() {
System.out.print("(");
ListElement d = head;
while(d != null)
{
System.out.print(d.first().toString() + " ");
d = d.rest();
}
System.out.println(")");
}
public int size() {
return count;
}
public void set(int n, Object o) {
// first, try to find n-1 and n+1; let's call them nMin and nPlus
ListElement nMin = null;
ListElement nPlus;
if (n > 0) {
// if we're not setting element with index 0, we can run through the linked list
nMin = head;
while (n-1 < 0) {
nMin = nMin.rest();
n--;
}
// and we can use n-1 to find n+1
nPlus = nMin.rest().rest()
} else {
// Otherwise, n+1 is really just element with index 1, or head.rest()
// in this case, nMin doesn't exist, so we let it be 0
nPlus = head.rest();
}
// turn this element into a ListElement and make it point to n+1
// because we're going to insert this element between n-1 and n+1
ListElement thisObject = new ListElement(o, nPlus);
// if nMin is null, that means we're making a new head, so just assing the new object to the head
if (nMin == null) {
head = thisObject;
} else {
// otherwise, make n-1 point to this element
nMin.setRest(thisObject);
}
// and we're done. obviously, this could fail in a number of ways, most likely nullpointer exceptions because we're not sanitising the "n" parameter at all. but whatever.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment