Created
September 20, 2015 04:04
-
-
Save dag10/1eec139709b1c9189ac7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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