Advertisement
Yesver08

SLLC.java

Mar 8th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. import java.util.NoSuchElementException;
  2.  
  3. public class SLLC {
  4.     NodeSLLC head, tail;
  5.     int size;
  6.  
  7.     SLLC() {
  8.         head = tail = null;
  9.         size = 0;
  10.     }
  11.  
  12.     boolean isEmpty() {
  13.         return size == 0;
  14.     }
  15.  
  16.     void addFirst(NodeSLLC input) {
  17.         if (isEmpty()) {
  18.             head = tail = input;
  19.             tail.next = head;
  20.         }
  21.         else {
  22.             input.next = head;
  23.             tail.next = input;
  24.             head = input;
  25.         }
  26.         size++;
  27.     }
  28.  
  29.     void addLast(NodeSLLC input) {
  30.         if (isEmpty()) {
  31.             head = tail = input;
  32.             tail.next = head;
  33.         }
  34.         else {
  35.             tail.next = input;
  36.             input.next = head;
  37.             tail = input;
  38.         }
  39.         size++;
  40.     }
  41.  
  42.     void removeFirst() {
  43.         if (!isEmpty()) {
  44.             if (size == 1) head = tail = null;
  45.             else {
  46.                 NodeSLLC temp = head.next;
  47.                 tail.next = temp;
  48.                 head = temp;
  49.             }
  50.             size--;
  51.         }
  52.         else throw new NoSuchElementException();
  53.     }
  54.  
  55.     void removeLast() {
  56.         if (!isEmpty()) {
  57.             if (size == 1) head = tail = null;
  58.             else {
  59.                 NodeSLLC temp = head;
  60.                 while (temp.next != tail) {
  61.                     temp = temp.next;
  62.                 }
  63.                 temp.next = head;
  64.                 tail = temp;
  65.             }
  66.             size--;
  67.         }
  68.         else throw new NoSuchElementException();
  69.     }
  70.  
  71.     private void checkIndex(int index) {
  72.         if (index < 0 || index >= size) throw new IndexOutOfBoundsException();
  73.     }
  74.  
  75.     Object get(int index) {
  76.         checkIndex(index);
  77.         NodeSLLC temp = head;
  78.         for (int i = 0; i < index; i++) temp = temp.next;
  79.         return temp.data;
  80.     }
  81.  
  82.     @Override
  83.     public String toString() {
  84.         NodeSLLC p = head;
  85.         String s = "[";
  86.         for (int i = 0; i < size; i++) {
  87.             if (i != 0) s += ", ";
  88.             s += p.data;
  89.             p = p.next;
  90.         }
  91.         s += "]";
  92.         return s;
  93.     }
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement