Friday, December 6, 2013
a simple double linked list in Java
class Node {
public int data;
public Node prev;
public Node next;
}
class LinkList {
private Node head;
// LinkList constructor
public LinkList() {
head = null;
}
// Returns true if list is empty
public boolean isEmpty() {
return head == null;
}
// Inserts a new Node at the head of the list
public void insert(int a) {
Node node = new Node();
node.data = a;
node.prev = null;
node.next = null;
if (head == null)
head = node;
else
{
// All below stuff is to find the last node.
Node cursor=head;
Node last = head;
while(cursor != null)
{
if (cursor.next == null) last = cursor;
cursor = cursor.next;
}
// Now insert new node at the end of list.
last.next = node;
node.prev = last;
}
}
// Top the node at the head of the list
public void top() {
head = head.next;
head.prev = null;
}
// Prints list data
public void printList() {
Node cursor = head;
System.out.print("List: ");
while (cursor != null) {
System.out.print(cursor.data + " ");
cursor = cursor.next;
}
System.out.println("");
}
public void printListBackwards() {
Node cursor=head;
Node last = head;
while(cursor != null)
{
// Find the last node.
if (cursor.next == null) last = cursor;
cursor = cursor.next;
}
cursor = last;
System.out.print("List: ");
while (cursor != null) {
System.out.print(cursor.data + " ");
cursor = cursor.prev;
}
System.out.println("");
}
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1);
list.insert(2);
list.insert(3);
list.printList();
list.printListBackwards();
list.top();
list.printList();
list.printListBackwards();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment