Skip to content

Instantly share code, notes, and snippets.

@biskandar
Created October 21, 2016 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biskandar/c22de0c5c02311f9ae75657d75e83e06 to your computer and use it in GitHub Desktop.
Save biskandar/c22de0c5c02311f9ae75657d75e83e06 to your computer and use it in GitHub Desktop.
Java: Double Linked List
package com.careercup.linkedlist;
public class DoubleLinkedList<AnyType> {
private Node<AnyType> nodeFirst;
private Node<AnyType> nodeLast;
private Node<AnyType> nodeIndex;
public DoubleLinkedList() {
nodeFirst = null;
nodeLast = null;
}
public void iterReset() {
nodeIndex = nodeFirst;
}
public AnyType iterNext() {
AnyType data = null;
if (nodeIndex != null) {
data = nodeIndex.getData();
}
Node<AnyType> nodeNext = nodeIndex.getNext();
if (nodeNext != null) {
nodeIndex = nodeNext;
}
return data;
}
public AnyType iterPrev() {
AnyType data = null;
if (nodeIndex != null) {
data = nodeIndex.getData();
}
Node<AnyType> nodePrev = nodeIndex.getPrev();
if (nodePrev != null) {
nodeIndex = nodePrev;
}
return data;
}
public void addLast( AnyType data ) {
Node<AnyType> nodeNew = new Node<AnyType>(data);
if (nodeFirst == null) {
nodeFirst = nodeLast = nodeNew;
return;
}
nodeNew.setPrev(nodeLast);
nodeLast.setNext(nodeNew);
nodeLast = nodeNew;
}
public void addFirst( AnyType data ) {
Node<AnyType> nodeNew = new Node<AnyType>(data);
if (nodeFirst == null) {
nodeFirst = nodeLast = nodeNew;
return;
}
nodeNew.setNext(nodeFirst);
nodeFirst.setPrev(nodeNew);
nodeFirst = nodeNew;
}
public class Node<AnyType> {
private AnyType data;
private Node<AnyType> next;
private Node<AnyType> prev;
public Node( AnyType data ) {
this.data = data;
}
public Node<AnyType> getNext() {
return next;
}
public void setNext( Node<AnyType> next ) {
this.next = next;
}
public Node<AnyType> getPrev() {
return prev;
}
public void setPrev( Node<AnyType> prev ) {
this.prev = prev;
}
public AnyType getData() {
return data;
}
}
public static void main( String[] args ) {
DoubleLinkedList<Integer> list = new DoubleLinkedList<>();
list.addLast(2);
list.addLast(3);
list.addFirst(1);
list.addFirst(0);
list.iterReset();
for (int idx = 0; idx < 8; idx++) {
System.out.printf("%d ", list.iterNext());
}
System.out.println();
for (int idx = 0; idx < 8; idx++) {
System.out.printf("%d ", list.iterPrev());
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment