Created
August 2, 2017 00:14
-
-
Save alexleventer/b4f7c821298680f2e33519649441d85e to your computer and use it in GitHub Desktop.
LinkedList
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
package cpsc5002_02; | |
public class LinkedListPlay { | |
private static class Node { | |
public double payload; | |
public Node next; | |
public Node(double payload, Node next) { | |
this.payload = payload; | |
this.next = next; | |
} | |
} | |
private static Node head = null; | |
public static void main(String[] args) { | |
insertAtBeginning(100.6); | |
insertAtBeginning(-14.1); | |
insertAtBeginning(6.2); | |
insertAtBeginning(7.8); | |
insertAtBeginning(10000.6); | |
insertAtBeginning(10.69); | |
System.out.println("full list"); | |
printLinkedList(); | |
removeFromBeginning(); | |
System.out.println("one less"); | |
printLinkedList(); | |
removeFromBeginning(); | |
removeFromBeginning(); | |
removeFromBeginning(); | |
removeFromBeginning(); | |
removeFromBeginning(); | |
System.out.println("empty list"); | |
printLinkedList(); | |
removeFromBeginning(); | |
insertAtBeginning(1); | |
insertAtBeginning(2); | |
Node pred = head; | |
insertAtBeginning(3); | |
insertAtNode(pred,4); | |
System.out.println("inserted in the middle"); | |
printLinkedList(); | |
removeAtNode(pred); | |
System.out.println("deleted the 4 from the middle"); | |
printLinkedList(); | |
} | |
private static void insertAtBeginning(double payload) { | |
head = new Node(payload, head); | |
} | |
private static void removeFromBeginning() { | |
if (head != null) | |
head = head.next; | |
} | |
private static void insertAtNode(Node predecessor, double payload) { | |
if (predecessor != null) | |
predecessor.next = new Node(payload, predecessor.next); | |
} | |
private static void removeAtNode(Node predecessor) { | |
if (predecessor != null) | |
predecessor.next = predecessor.next.next; | |
} | |
private static void insertNth(int n, double payload) { | |
if (n == 0) { | |
insertAtBeginning(payload); | |
} else { | |
Node p = head; | |
for (int i = 1; i < n; i++) { | |
p = p.next; | |
if (p == null) | |
throw new IllegalArgumentException("list only has " + i + " nodes"); | |
} | |
insertAtNode(p, payload); | |
} | |
} | |
private static void printLinkedList() { | |
for (Node q = head; q != null; q = q.next) | |
System.out.println(q.payload); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment