Last active
October 20, 2016 19:42
-
-
Save ZacharyJacobCollins/c9ccdb2dda2ad3ab65eec65b8ef5367e to your computer and use it in GitHub Desktop.
Linked List Implementation in Java
This file contains hidden or 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
public class LinkedList { | |
private Node head; | |
public int listCount; | |
public LinkedList() { | |
head = new Node(""); | |
listCount = 1; | |
} | |
public void add(String data) { | |
Node temp = new Node(data); | |
Node current = this.head; | |
//starting at the head node, increment towards the end of the list | |
while(current.getNext() != null) { | |
current = current.getNext(); | |
} | |
current.setNext(temp); | |
listCount++; | |
} | |
//Prints the linked list | |
public void print() { | |
//Set the current node to the head | |
Node current = this.head; | |
//Where .getNext is a method/function call that returns the next in the line | |
while(current.getNext() != null) { | |
System.out.println(current.getData()); | |
current = current.getNext(); | |
} | |
System.out.println(current.getData()); | |
} | |
public static void main(String[] args) { | |
LinkedList l = new LinkedList(); | |
String s = new String(); | |
s = "press"; | |
l.add(s); | |
s = "f"; | |
l.add(s); | |
s = "to"; | |
l.add(s); | |
s = "pay"; | |
l.add(s); | |
s = "respects"; | |
l.add(s); | |
System.out.println(l.listCount); | |
l.print(); | |
} | |
class Node { | |
// reference to the next node in the chain, or null if there isn't one. | |
Node next; | |
// data carried by this node. could be of any type you need. | |
String data; | |
// Node constructor | |
public Node(String s) { | |
next = null; | |
data = s; | |
} | |
// another Node constructor if we want to specify the node to point to. | |
@SuppressWarnings("unused") | |
public Node(String dataString, Node nextValue) { | |
next = nextValue; | |
data = dataString; | |
} | |
// these methods should be self-explanatory | |
public Object getData() { | |
return data; | |
} | |
@SuppressWarnings("unused") | |
public void setData(String dataString) { | |
data = dataString; | |
} | |
public Node getNext() { | |
return next; | |
} | |
public void setNext(Node nextValue) { | |
next = nextValue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment