LinkedList.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
class Node { int data; Node next; public Node(int data){ this.data = data; } public Node(int data, Node next){ this(data); this.next = next; } public String toString(){ return "" + data; } } public class LinkedList { private Node head, tail; private int count; public LinkedList(){ head = tail = null; count = 0; } public LinkedList(int d){ head = tail = new Node(d); count = 1; } public void append(int d){ //Node n = new Node(d); //tail.next = n; //tail = n; if (isEmpty()) head = tail = new Node(d); else tail = tail.next = new Node(d); count++; } public void prepend(int d){ //Node n = new Node(d, head); //head = n; //Node n = new Node(d); //n.next = head; //head = n; if (isEmpty()) head = tail = new Node(d); else head = new Node(d, head); count++; } public String toString(){ String retVal = "Linked List with " + count + " nodes: "; //Node temp = head; //while (temp != null){ // retVal += temp + " "; // temp = temp.next //} for (Node temp = head ; temp != null ; temp = temp.next){ retVal += temp + " "; } return retVal; } /* You implement: * public void insert(int data, int boolean) * public boolean exists(int data) * public boolean remove(int data) * public int get(int index) */ } |
Main.java
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] a) { LinkedList ll = new LinkedList(5); ll.prepend(3); ll.append(1); System.out.println(ll.toString()); } } |