Created
December 7, 2014 04:51
-
-
Save h2rashee/33486e3360d529834689 to your computer and use it in GitHub Desktop.
LinkedList ADT
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 LinkedLists | |
{ | |
public static void main(String[] args) { | |
LinkedList llist = new LinkedList(); | |
// Use LinkedLIst class API here | |
} | |
} | |
class LinkedList | |
{ | |
Node ll; | |
// Insert a node into a list | |
public void insert(int val) { | |
// Empty list case | |
if(ll == null) { | |
ll = new Node(val); | |
} else { | |
// Otherwise insert value at the head | |
Node n = new Node(val); | |
n.next = ll; | |
ll = n; | |
} | |
} | |
// Remove a node from a list given the value it contains | |
public void remove(int val) { | |
Node n = ll; | |
// Empty list | |
if(ll == null) { | |
System.err.println("Couldn't find value to remove"); | |
return; | |
} | |
// First node is a match | |
if(ll.val == val) { | |
ll = ll.next; | |
return; | |
} | |
// Iterate to find node with value | |
while(n.next.val != val) { | |
// Value not in list | |
if(n.next == null) { | |
System.err.println("Couldn't find value to remove"); | |
return; | |
} | |
n = n.next; | |
} | |
// Release the node from the list | |
n.next = n.next.next; | |
} | |
// Reverse the list | |
public void reverse() { | |
Node p = ll; | |
// Empty list or single node list | |
if(p == null || p.next == null) { | |
return; | |
} | |
// Thread the pointers backwards | |
Node c = p.next; | |
p.next = null; | |
Node n = c.next; | |
c.next = p; | |
// Until we reach the end of the list | |
while(n != null) { | |
p = c; | |
c = n; | |
n = c.next; | |
c.next = p; | |
} | |
ll = c; | |
} | |
public void printList() { | |
Node n = ll; | |
// Dump the node contents until we reach the end of the list | |
while(n != null) { | |
System.out.println("Node value: " + n.val); | |
n = n.next; | |
} | |
} | |
private int getSize() { | |
Node n = ll; | |
int size = 0; | |
while(n != null) { | |
size++; | |
n = n.next; | |
} | |
return size; | |
} | |
} | |
class Node | |
{ | |
int val; | |
Node next; | |
public Node(int val_) { | |
val = val_; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment