User Tools

Site Tools


linkedlistjava

A linked list implementation in Java. Acts as a stack, allows to push and pop elements, as well reversing the list and searching and deleting an element.

package ch.ethz.da.serie05;
 
/**
 * A simple stack based on a single linked list.
 * 
 * @author Moritz Hoffmann
 * 
 * @param <D>
 *            The list data type.
 */
public class MyList<D> {
 
    private static class Element<D> {
        private D data;
        private Element<D> next;
    }
 
    Element<D> head;
 
    public MyList() {
        head = null;
    }
 
    public boolean contains(D data) {
        Element<D> current = head;
        while (current != null) {
            if (current.data.equals(data)) {
                return true;
            }
            current = current.next;
        }
        return false;
    }
 
    public void delete(D data) {
        if (head != null) {
            if (head.data.equals(data)) {
                // Kopf loeschen
                head = head.next;
            } else {
                // Element nach Kopf loeschen
                Element<D> current = head;
                while (current.next != null) {
                    if (current.next.data.equals(data)) {
                        current.next = current.next.next;
                        break;
                    }
                    current = current.next;
                }
            }
        }
    }
 
    public void insert(D data) {
        Element<D> e = new Element<D>();
        e.data = data;
        e.next = head;
        head = e;
    }
 
    public D pop() {
        D data = null;
        if (head != null) {
            data = head.data;
            head = head.next;
        }
        return data;
    }
 
    public void reverse() {
        Element<D> current = head;
        Element<D> temporary = null;
        Element<D> last = null;
        while (current != null) {
            temporary = current.next;
            current.next = last;
            last = current;
            current = temporary;
        }
        head = last;
    }
 
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        Element<D> current = head;
        while (current != null) {
            sb.append(current.data);
            current = current.next;
            if (current != null) {
                sb.append(", ");
            }
        }
        return sb.append("]").toString();
    }
}
linkedlistjava.txt · Last modified: 2009/03/28 19:20 by moritz