Advertisement
korobushk

sLiList

Apr 2nd, 2021
690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. package ds.cs61b;
  2.  
  3. // a SLList is a list of intergers, which hides the terrible truth of the nakedness within
  4.  
  5. public class SLList<LochNess> {
  6.     public class StuffNode {
  7.         public LochNess item;
  8.         public StuffNode next;
  9.  
  10.         public StuffNode(LochNess i, StuffNode n) {
  11.             item = i;
  12.             next = n;
  13.         }
  14.  
  15.         public void displayNode() {
  16.             System.out.println("{ " + item + " } ");
  17.         }
  18.     }
  19.  
  20.     private StuffNode sentinel;
  21.     private int size;
  22.  
  23.  
  24.     public SLList(LochNess x) {
  25.         sentinel = new StuffNode(x, null);
  26.         sentinel.next = new StuffNode(x, null);
  27.  
  28.         size += 1;
  29.     }
  30.  
  31.     /**
  32.      * Adds an item to the front of the list.
  33.      */
  34.     public void addFirst(LochNess x) {
  35.         sentinel.next = new StuffNode(x, sentinel.next);
  36.         size += 1;
  37.  
  38.     }
  39.  
  40.     /**
  41.      * Retrieves the front item from the list.
  42.      */
  43.     public LochNess getFirst() {
  44.         return sentinel.next.item;
  45.     }
  46.  
  47.     /**
  48.      * Adds an item to the end of the list.
  49.      */
  50.     public void addLast(LochNess x) {
  51.         size += 1;
  52.         StuffNode p = sentinel;
  53.  
  54.         while (p.next != null) {
  55.             p = p.next;
  56.         }
  57.         p.next = new StuffNode(x, null);
  58.  
  59.  
  60.     }
  61.  
  62.     public int size3() {
  63.         return size;
  64.     }
  65.  
  66.     /**
  67.      * Returns the number of items in the list using recursion.
  68.      */
  69.  
  70.  
  71.     public int size() {
  72.         return size;
  73.  
  74.     }
  75.  
  76.     public void displayList() {
  77.         System.out.println("List (first --> last) ");
  78.         StuffNode current = sentinel.next;
  79.         while (current != null) {
  80.             current.displayNode();
  81.             current = current.next;
  82.         }
  83.         System.out.println();
  84.     }
  85. }
  86.  
  87. //    public int size() {
  88. //        StuffNode p = sentinel;
  89. //        int count = 1;
  90. //
  91. //        while (p.next != null) {
  92. //            p = p.next;
  93. //            count++;
  94. //        }
  95. //
  96. //        return count;
  97. //    }
  98. //
  99. //    public static int size2(SLList.StuffNode p) {
  100. //        if (p.next == null) {
  101. //            return 1;
  102. //        }
  103. //        return 1 + size2(p.next);
  104. //
  105. //    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement