Advertisement
gon2

SInglyLinkedLIst með swap

Mar 13th, 2018
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.21 KB | None | 0 0
  1. import edu.princeton.cs.algs4.StdOut;
  2. import edu.princeton.cs.algs4.StdRandom;
  3.  
  4. import java.util.Iterator;
  5.  
  6. public class SinglyLinkedList<T> implements Iterable<T> {
  7.  
  8.  
  9.     private class Node {
  10.  
  11.         Node next;
  12.         T data;
  13.  
  14.         Node(T data, Node next) {
  15.             this.data = data;
  16.             this.next = next;
  17.         }
  18.     }
  19.  
  20.     private Node head;
  21.     private int length;
  22.  
  23.     SinglyLinkedList() {
  24.         /*
  25.         Smiður sem upphafsstillir tóman lista.
  26.          */
  27.         this.head = null;
  28.         this.length = 0;
  29.     }
  30.  
  31.     public boolean isEmpty() {
  32.         /*
  33.         Skilar sönnu innihaldi listinn engin stök, annars ósönnu
  34.          */
  35.         return this.head == null;
  36.     }
  37.  
  38.     public int size() {
  39.         /*
  40.         Skilar fjölda staka í listanum.
  41.          */
  42.         return this.length;
  43.     }
  44.  
  45.     @Override
  46.     public String toString() {
  47.         /*
  48.         Aðferð sem sýnir fallega strengjaframsetningu á listanum.
  49.          */
  50.         Node node = this.head;
  51.         String representation = "";
  52.         while (node != null) {
  53.             representation += node.data.toString() + " -> "; // Ath. að þetta er ekki skilvirkt, dekkum seinna
  54.             node = node.next;
  55.         }
  56.         return representation + "Ø";
  57.     }
  58.  
  59.     public T get(int index) {
  60.         /*
  61.         Skilar staki númer <index> í listanum án þess að breyta honum.
  62.          */
  63.         if (index < 0 || this.size() <= index) {
  64.             throw new ArrayIndexOutOfBoundsException("Vísað út fyrir lista");
  65.         }
  66.  
  67.         Node node = this.head;
  68.         int i = 0;
  69.         while (node != null) {
  70.             if (i == index) {
  71.                 return node.data;
  72.             }
  73.             node = node.next;
  74.             i++;
  75.         }
  76.         return null;
  77.     }
  78.  
  79.     public void insert(int index, T data) {
  80.         /*
  81.         Bætir staki við listann í sæti númer <index>, án þess að yfirskrifa stak.
  82.         Öllum stökum sem koma á eftir nýja stakinu hliðrast í átt að enda listans.
  83.          */
  84.         if (index < 0 || this.size() < index) {
  85.             throw new ArrayIndexOutOfBoundsException("Vísað út fyrir lista");
  86.         }
  87.         if (index == 0) {
  88.             this.head = new Node(data, this.head);
  89.         } else {
  90.             Node node = this.head;
  91.             int i = 0;
  92.             while (node.next != null && i < index - 1) {
  93.                 node = node.next;
  94.                 i++;
  95.             }
  96.             node.next = new Node(data, node.next);
  97.         }
  98.         this.length++;
  99.     }
  100.  
  101.     public void delete(int index) {
  102.         /*
  103.         Fjarlægir stak númer <index> úr listanum og uppfærir <this.length>.
  104.         Númer allra staka sem komu á eftir stakinu sem var eytt skulu lækka.
  105.          */
  106.         if (index < 0 || this.size() <= index) {
  107.             throw new ArrayIndexOutOfBoundsException("Vísað út fyrir lista");
  108.         }
  109.        
  110.         // fyrsta stakið í listanum:
  111.         if (index == 0) {
  112.             Node del = this.head; // eyðum þessum hnút
  113.             Node eftir = del.next; // hnúturinn á eftir
  114.             del = null; // eyðum tilvísunum
  115.             this.head = eftir;
  116.            
  117.         // síðasta stakið í listanum:
  118.         } else if (index == this.size()-1) {
  119.             Node undan = this.head;
  120.             for (int i=0; i<index-1; i++) undan = undan.next; // hnúturinn á undan þeim sem við viljum eyða
  121.             Node del = undan.next; // hnúturinn sem við viljum eyða
  122.             undan.next = null;
  123.             del = null; // eyðum tilvísunum
  124.            
  125.         // eyðum staki í miðjum lista:  
  126.         } else {
  127.             Node undan = this.head;
  128.             for (int i=0; i<index-1; i++) undan = undan.next; // hnúturinn á undan þeim sem við viljum eyða
  129.             Node del = undan.next; // hnúturinn sem við viljum eyða
  130.             Node eftir = del.next; // hnúturinn á eftir þeim sem við eyðum
  131.             undan.next = eftir; // tengjum undan og eftir saman
  132.             del = null; // eyðum tilvísunum
  133.         }
  134.        
  135.         this.length--; // minnkum lengd listans um einn
  136.     }
  137.  
  138.     public void swap(int index1, int index2) {
  139.         /*
  140.         Skiptir á staðsetningum hnúta númer <index1> og <index2> með
  141.         því að uppfæra vísanir nágranna þeirra.
  142.         Ekki er tryggt að <index1> sé minni en <index2>.
  143.          */
  144.         if (index1 < 0 || index2 < 0 || this.size() <= index1 || this.size() <= index2) {
  145.             throw new ArrayIndexOutOfBoundsException("Vísað út fyrir lista");
  146.         }
  147.        
  148.         // skilgreiningar
  149.         Node undan = this.head;
  150.         Node undan2 = this.head;
  151.         Node swap = null;
  152.         Node swap2 = null;
  153.         Node eftir = null;
  154.         Node eftir2 = null;
  155.        
  156.         if (index1 == index2) return; // ef jafnt þá gerum við ekkert
  157.        
  158.         // ef annaðhvort er fyrsta stak:
  159.         if (index1 == 0) swap = this.head;
  160.         if (index2 == 0) swap2 = this.head;
  161.        
  162.         for (int i=0; i<this.size(); i++) {
  163.             // finnum hnúta á undan
  164.             if (i < index1-1) undan = undan.next;
  165.             if (i < index2-1) undan2 = undan2.next;
  166.            
  167.             if (i>=index1 && i>=index2) { // þegar búið er að finna hnúta á undan
  168.                 // finnum hnúta á eftir
  169.                 if (index1 != 0) swap = undan.next;
  170.                 if (index1 != this.size()-1) eftir = swap.next;
  171.                 if (index2 != 0) swap2 = undan2.next;
  172.                 if (index2 != this.size()-1) eftir2 = swap2.next;
  173.                
  174.                 // skiptum á vísunum
  175.                 if (index1 != 0) undan.next = swap2;
  176.                 if (index1 != this.size()-1) swap2.next = eftir;
  177.                 if (index2 != 0) undan2.next = swap;
  178.                 if (index2 != this.size()-1) swap.next = eftir2;
  179.                
  180.                 // ef við erum með síðasta hnút
  181.                 if (index1 == this.size()-1) swap2.next = null;
  182.                 if (index2 == this.size()-1) swap.next = null;
  183.                
  184.                 // ef við erum með fyrsta hnút
  185.                 if (index1 == 0) this.head = swap2;
  186.                 if (index2 == 0) this.head = swap;
  187.                                
  188.                 return;    
  189.             }
  190.         }
  191.  
  192.  
  193.     }
  194.  
  195.     public Iterator<T> iterator() {
  196.         /*
  197.         Einfaldur ítrari fyrir SinglyLinkedList klasann, sjá ListIterator
  198.         */
  199.         return new ListIterator();
  200.     }
  201.  
  202.     private class ListIterator implements Iterator<T> {
  203.         private Node current = head;
  204.  
  205.         public boolean hasNext() {
  206.             return this.current != null;
  207.         }
  208.  
  209.         public void remove() {
  210.             throw new UnsupportedOperationException();
  211.         }
  212.  
  213.         public T next() {
  214.             T item = this.current.data;
  215.             this.current = this.current.next;
  216.             return item;
  217.         }
  218.     }
  219.  
  220.     public static void main(String[] args) {
  221.         SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
  222.         list.insert(0, 2);
  223.         list.insert(0, 1);
  224.         list.insert(2, 4);
  225.         list.insert(2, 3);
  226.         StdOut.println("Listinn er í upphafi:          " + list);
  227.         StdOut.println("");
  228.  
  229.         // Prófum swap aðferðina
  230.         StdOut.print("Skiptum á hnútum 1 og 3, ");
  231.         list.swap(1, 3);
  232.         StdOut.println("fáum: " + list);
  233.         StdOut.print("Lagfærum listann aftur, ");
  234.         list.swap(3, 1);
  235.         StdOut.println("fáum:  " + list);
  236.         StdOut.print("Prófum að skipta á endunum:    ");
  237.         list.swap(0, list.size() - 1);
  238.         StdOut.println(list);
  239.         StdOut.print("Lagfærum aftur:                ");
  240.         list.swap(list.size() - 1, 0);
  241.         StdOut.println(list);
  242.  
  243.         // Prófum delete aðferðina
  244.         StdOut.println("");
  245.         StdOut.println("Hendum nú út öllum hnútunum í slembinni röð");
  246.  
  247.         int max = 10, count = 0; // Svo lykkjan keyri ekki endalaust þegar eyðingin er ókláruð
  248.         int index = 0;
  249.         while (!list.isEmpty() && count++ < max) {
  250.             index = StdRandom.uniform(0, list.size()); // Veljum stak af handahófi
  251.             StdOut.print("Hendum staki númer " + index);
  252.             list.delete(index);
  253.             StdOut.println(". Eftir eyðingu er listinn: " + list);
  254.         }
  255.     }
  256. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement