Skip to content

Instantly share code, notes, and snippets.

@zwilias
Created October 22, 2012 22:29
Show Gist options
  • Save zwilias/3935059 to your computer and use it in GitHub Desktop.
Save zwilias/3935059 to your computer and use it in GitHub Desktop.
Add a method addLast() which adds an element to the end of the linked list.
public class Assignment {
/**
* @param args
*/
public static void main(String[] args) {
// create list
LinkedList list = new LinkedList();
// initialize list
for (int i = 4; i >= 1; i--) {
list.addFirst(i);
}
// print list
list.print();
// list size
System.out.println(list.size());
// replace element
list.set(3, 777);
// print list
list.print();
// get the last entry
System.out.println(list.getLast());
// add last
list.addLast(123);
// add last
// print list
list.print();
// add last
list.addLast(123);
// print list
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, tail;
private int count;
public LinkedList()
{
head = null;
}
public void addFirst(Object o)
{
head = new ListElement(o,head);
count++;
if (count == 1) {
tail = head;
}
}
public void addLast(Object o)
{
ListElement newTail = new ListElement(o);
tail.setRest(newTail);
tail = newTail;
}
public Object get(int n)
{
ListElement d = head;
while(n>0)
{
d = d.rest();
n--;
}
return d.first();
}
public Object getFirst()
{
return head.first();
}
public Object getLast()
{
return tail.first();
}
public void print()
{
System.out.print("Complete list = ");
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) {
ListElement d = head;
while (n > 0) {
d = d.rest();
n--;
}
d.setFirst(o);
}
public int indexOf(Object o) {
int index = -1;
int counter = 0;
boolean found = false;
ListElement elem = head;
while (!found && elem != null) {
found = elem.first().equals(o);
if (!found) {
counter += 1;
elem = elem.rest();
}
}
if (found) {
index = counter;
}
return index;
}
public boolean contains(Object o) {
return indexOf(o) > 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment