WallHero

TP04E04 SimpleLinkedList

Oct 30th, 2020
659
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Iterator;
  2.  
  3. public class SimpleLinkedList <ELEMENT extends Comparable> implements Iterable<ELEMENT> {
  4.     private Node<ELEMENT> head;
  5.     private int count;
  6.     private Node<ELEMENT> tail;
  7.    
  8.    
  9.     public void addFirst(ELEMENT data)
  10.     {
  11.         Node<ELEMENT> temp = new Node<ELEMENT>(data, this.head);
  12.         if(this.count++ == 0) this.tail = temp;
  13.         this.head = temp;
  14.     }
  15.    
  16.     public void addLast(ELEMENT data)
  17.     {
  18.         Node<ELEMENT> temp = new Node<ELEMENT>(data,null);
  19.         if(this.count++ == 0)
  20.         {
  21.             this.head = temp;
  22.         }
  23.         else this.tail.next = temp;
  24.         this.tail = temp;
  25.     }
  26.    
  27.     public void addSort(ELEMENT data)
  28.     {
  29.         if(this.count == 0) addFirst(data);
  30.         else if(data.compareTo(this.head.item) < 0) addFirst(data);
  31.         else if(data.compareTo(this.tail.item) > 0) addLast(data);
  32.         else
  33.         {
  34.             SimpleLinkedListIterator<ELEMENT> begin = new SimpleLinkedListIterator<ELEMENT>(this.head);
  35.             while(begin.hasNext() && data.compareTo(begin.next()) > 0);
  36.             Node<ELEMENT> next = begin.nextNode();
  37.             Node<ELEMENT> temp = new Node<ELEMENT>(data, next);
  38.             next.next = temp;
  39.         }
  40.     }
  41.    
  42.     @Override
  43.     public Iterator<ELEMENT> iterator() {
  44.         // TODO Auto-generated method stub
  45.         return new SimpleLinkedListIterator<ELEMENT>(this.head);
  46.     }
  47.    
  48. }
  49.  
  50.  
RAW Paste Data