Skip to content

Instantly share code, notes, and snippets.

@dag10
Created September 20, 2015 04:04
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 dag10/1eec139709b1c9189ac7 to your computer and use it in GitHub Desktop.
Save dag10/1eec139709b1c9189ac7 to your computer and use it in GitHub Desktop.
class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
next = null;
}
public int getValue() {
return value;
}
public void setNext(Node next) {
this.next = next;
}
public Node getNext() {
return next;
}
}
class LinkedList {
private Node head;
private Node tail;
public LinkedList() {
head = null;
tail = null;
}
public void add(int value) {
Node newNode = new Node(value);
if (tail == null) {
tail = newNode;
head = newNode;
} else {
tail.setNext(newNode);
tail = newNode;
}
}
public void print() {
Node currentNode = head;
while (currentNode != null) {
System.out.println(currentNode.getValue());
currentNode = currentNode.getNext();
}
}
public int removeFromHead() {
int val = head.getValue();
head = head.getNext();
return val;
}
}
public class Example {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
System.out.println("Our list:");
list.print();
System.out.println();
System.out.println("Removed: " + list.removeFromHead());
System.out.println("Removed: " + list.removeFromHead());
System.out.println("Removed: " + list.removeFromHead());
System.out.println("Removed: " + list.removeFromHead());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment