Advertisement
xickoh

Add LinearNodes to an OrderedList

Dec 22nd, 2020 (edited)
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package ed_ficha08;
  7.  
  8. /**
  9.  *
  10.  * @author franc
  11.  */
  12. public class OrderedList<T> extends LinkedList<T> implements OrderedListADT<T> {
  13.  
  14.     LinearNode front;
  15.     LinearNode rear;
  16.     private int size;
  17.  
  18.     public void add(T element) {
  19.         LinearNode newNode = new LinearNode((Comparable<T>) element);
  20.  
  21.         //If there's no elements yet
  22.         if (this.size == 0) {
  23.             this.front = new LinearNode((Comparable<T>) element);
  24.             this.rear = new LinearNode((Comparable<T>) element);
  25.             this.rear = this.front = newNode;
  26.             this.front.setNext(this.rear);
  27.             this.rear.setNext(null);
  28.             this.size++;
  29.         } else {
  30.  
  31.             //There are elements in the list already
  32.             LinearNode searchingNode = this.front;
  33.             LinearNode previousNode = new LinearNode();
  34.  
  35.             //Iterate the list
  36.             while (searchingNode != null) {
  37.                 if (searchingNode.compareTo(newNode) < 0) {
  38.                     previousNode = searchingNode;
  39.                     searchingNode = searchingNode.getNext();
  40.                 } else {
  41.  
  42.                     //If it's the first item in the order, it has to be inserted in the front
  43.                     if (searchingNode.equals(this.front)) {
  44.                         LinearNode temp = searchingNode;
  45.                         this.front = newNode;
  46.                         this.front.setNext(temp);
  47.                     } else {
  48.                         //If it belongs in the middle
  49.                         newNode.setNext(previousNode.getNext());
  50.                         previousNode.setNext(newNode);
  51.                     }
  52.                     this.size++;
  53.                     return;
  54.                 }
  55.             }
  56.  
  57.             //It's the last item in the order
  58.             this.rear.setNext(newNode);
  59.             this.rear = newNode;
  60.             this.size++;
  61.         }
  62.     }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement