daily pastebin goal
63%
SHARE
TWEET

Untitled

a guest Dec 16th, 2018 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Node header;
  2.  
  3. public DoublyLinkedDeleteFirst() {
  4.     header = new Node();
  5. }
  6.  
  7. //removes the node at position 1 and returns
  8. //the string contained in that node
  9. public String deleteFirst() {
  10.     //implement
  11.     Node temp = header;
  12.  
  13.     try {
  14.         temp = temp.next.next;
  15.         Node deleted = temp;
  16.  
  17.         temp.previous.next = temp.next;
  18.         temp.next.previous = deleted.previous;
  19.         return deleted.value;
  20.     }catch (NullPointerException e) {
  21.         throw new IllegalStateException();
  22.     }
  23.  
  24. }
  25.  
  26. public boolean isEmpty() {
  27.     if(header == null)
  28.         return true;
  29.     return false;
  30. }
  31.  
  32. // adds to the end of the list
  33. public void addLast(String item) {
  34.     Node next = header;
  35.     while (next.next != null) {
  36.         next = next.next;
  37.     }
  38.     Node n = new Node();
  39.     n.value = item;
  40.     next.next = n;
  41.     n.previous = next;
  42.  
  43. }
  44.  
  45. @Override
  46. public String toString() {
  47.  
  48.     StringBuilder sb = new StringBuilder();
  49.     toString(sb, header);
  50.     return sb.toString();
  51.  
  52. }
  53.  
  54. private void toString(StringBuilder sb, Node n) {
  55.     if (n == null)
  56.         return;
  57.     if (n.value != null)
  58.         sb.append(" " + n.value);
  59.     toString(sb, n.next);
  60. }
  61.  
  62. class Node {
  63.     String value;
  64.     Node next;
  65.     Node previous;
  66.  
  67.     public String toString() {
  68.         return value == null ? "null" : value;
  69.     }
  70. }
  71.  
  72. public static void main(String[] args) {
  73.     DoublyLinkedDeleteFirst list = new DoublyLinkedDeleteFirst();
  74.     list.addLast("Inter Millan");
  75.     list.addLast("Barcelona");
  76.    //list.addLast("Manchester United");
  77.     String deleted = list.deleteFirst();
  78.     System.out.println("This item was deleted: " + deleted);
  79.     System.out.println(list);
  80.  }
  81. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top