Skip to content

Instantly share code, notes, and snippets.

@AnimaWish
Created January 15, 2014 19:48
Show Gist options
  • Save AnimaWish/8443153 to your computer and use it in GitHub Desktop.
Save AnimaWish/8443153 to your computer and use it in GitHub Desktop.
package LinkedList;
public class DoublyLinkedList<AnyType> {
private class Node {
public AnyType data;
Node next;
Node prev;
public Node(AnyType data) {
this.data = data;
}
}
public class Iterator {
int current;
DoublyLinkedList<AnyType> list;
public Iterator(int current, DoublyLinkedList<AnyType> list) {
this.current = current;
this.list = list;
}
public boolean valid() {
if(current < list.size()) {
return true;
} else {
return false;
}
}
public void next() {
if(current+1 < list.size()) {
current += 1;
}
}
public void prev() {
if(current-1 > 0) {
current -= 1;
}
}
public AnyType getData() {
if(this.valid()) {
// iteration = 0;
// cNode = list.head;
// while(iteration != current) {
// iteration += 1;
// cNode = cNode.next;
// }
Node cNode = index();
return cNode.data;
} else {
return null;
}
}
public void remove() {
if(this.valid()) {
// iteration = 0;
// cNode = list.head;
// while(iteration != current) {
// iteration += 1;
// cNode = cNode.next;
// }
Node cNode = index();
cNode.prev.next = cNode.next;
}
}
public void insert(AnyType data) {
Node cNode = index();
Node newNode = new Node(data);
newNode.next = cNode.next;
cNode.next = newNode;
}
private Node index() {
int iteration = 0;
Node cNode = list.head;
while(iteration != current) {
iteration += 1;
cNode = cNode.next;
}
return cNode;
}
}
Node head = new Node(null);
//CONSTRUCTOR
public DoublyLinkedList() {
}
//Adds a new Node to the front of the list
void add(AnyType data) {
Node newnode = new Node(data);
newnode.next = head;
head.prev = newnode;
head = newnode;
}
//Removes the first Node with the given data from the list
void remove(AnyType data) {
Node cNode = head;
while(cNode.data != data && cNode.data != null) {
cNode = cNode.next;
}
if(cNode.data == data) {
cNode.prev.next = cNode.next;
}
}
public int size() {
int listSize = 0;
Node cNode = head;
while(cNode.data != null) {
listSize += 1;
cNode = cNode.next;
}
return listSize;
}
public Iterator first() {
return new Iterator(0, this);
}
public Iterator last() {
int iteration = 0;
Node cNode = head;
while(cNode != null) {
cNode = cNode.next;
iteration += 1;
}
return new Iterator(iteration, this);
}
public Iterator find(AnyType data) {
int iteration = 0;
Node cNode = head;
while(cNode.data != data && cNode.data != null) {
cNode = cNode.next;
iteration += 1;
}
if(cNode.data == data) {
return new Iterator(iteration, this);
} else {
return new Iterator(-1, this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment