Friday, December 6, 2013
a simple linked list in java
class Node {
public int data;
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.next = null;
if (head == null)
head = node;
else
{
// All stuff below is to find the last node.
Node cursor = head;
Node last = head;
while (cursor != null)
{
// Find the last node.
if (cursor.next == null)
last = cursor;
cursor = cursor.next;
}
// Now insert node at the end of list.
last.next = node;
}
}
// Top the node at the head of the list
public void top() { head = head.next; }
// 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 static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1);
list.insert(2);
list.insert(3);
list.printList();
list.top();
list.top();
list.printList();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment