Advertisement
korobushk

delete node circular sll

Apr 27th, 2021
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1.  public void deleteNode(int location) {
  2.         if (head == null) {
  3.             System.out.println("The CSLL does not exist! ");
  4.             return;
  5.         } else if (location == 0) { //delete element from the beginning
  6.             head = head.next;  //more than one element
  7.             tail.next = head;
  8.             size--;
  9.             if (size == 0) {        // only one element in the CSLL
  10.                 tail = null;
  11.                 head.next = null;
  12.                 head = null;
  13.             }
  14.         } else if (location >= size) {      //delete element from the end
  15.             Node tempNode = head;
  16.             for (int i = 0; i < size - 1; i++) {
  17.                 tempNode = tempNode.next;
  18.             }
  19.             // go to the end
  20.  
  21.             if (tempNode == head) {  // has only one element
  22.                 head.next = null;
  23.                 tail = head = null;
  24.                 size--;
  25.                 return;
  26.             } //else we have more than one element
  27.  
  28.             tempNode.next = head;
  29.             tail = tempNode;
  30.             size--;
  31.  
  32.             //we added at the end
  33.         } else {
  34.             //deleting node from any location
  35.             Node tempNode = head;       //looping from the start
  36.             for (int i = 0; i < location - 1; i++) { //before location
  37.                 tempNode = tempNode.next;  //
  38.             }
  39.             tempNode.next = tempNode.next.next;
  40.             size--;
  41.         }
  42.     }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement