Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

find min/max in O(1) time

  • Loading branch information...
commit 25dc3706e20cff066ff181a33ef6552ad0ae8913 1 parent cb3171c
Anjali Shenoy authored April 19, 2012

Showing 1 changed file with 36 additions and 5 deletions. Show diff stats Hide diff stats

  1. 41  linked_list.rb
41  linked_list.rb
... ...
@@ -1,9 +1,10 @@
1 1
 class LinkedList
2 2
 
3  
-  attr_accessor :head, :last
  3
+  attr_accessor :head, :last, :min, :max
4 4
 
5 5
   def initialize
6 6
     self.head = Node.new
  7
+    self.min = self.max = nil
7 8
   end
8 9
 
9 10
   def add_to_head(data)
@@ -29,10 +30,31 @@ def add_to_tail(data)
29 30
       self.last.next = n
30 31
       self.last = n
31 32
     end
  33
+    update_min_max(n)
32 34
     self
33 35
   end
34 36
   alias_method :enqueue, :add_to_tail
35 37
 
  38
+  def update_min_max(node)
  39
+    update_min(node)
  40
+    update_max(node)
  41
+  end
  42
+  private :update_min_max
  43
+
  44
+  def update_max(node)
  45
+    if self.max.nil? || (node > self.max)
  46
+      self.max = node
  47
+    end
  48
+  end
  49
+  private :update_max
  50
+
  51
+  def update_min(node)
  52
+    if self.min.nil? || (node < self.min)
  53
+      self.min = node
  54
+    end
  55
+  end
  56
+  private :update_min
  57
+
36 58
   def drop_last
37 59
     n = self.head
38 60
     until (n.next == self.last)
@@ -186,7 +208,6 @@ def make_circle(start_position=1, end_position=self.size)
186 208
     puts self
187 209
     self
188 210
   end
189  
-
190 211
 end
191 212
 
192 213
 class Node
@@ -201,12 +222,20 @@ def to_s
201 222
   end
202 223
 
203 224
   def ===(other)
204  
-    self.data  = other.data
  225
+    self.data == other.data
205 226
   end
206 227
 
207 228
   def +(another_node)
208 229
     self.data + another_node.data
209 230
   end
  231
+
  232
+  def >(another_node)
  233
+    self.data > another_node.data
  234
+  end
  235
+
  236
+  def <(another_node)
  237
+    self.data < another_node.data
  238
+  end
210 239
 end
211 240
 
212 241
 ##stack
@@ -215,11 +244,13 @@ def +(another_node)
215 244
 #puts l.pop
216 245
 #puts l
217 246
 l = LinkedList.new
218  
-l.enqueue("a").enqueue("x").enqueue("c")
  247
+l.enqueue("z").enqueue("x").enqueue("c")
219 248
 #l.dequeue
220 249
 l.enqueue("a").enqueue("b").enqueue("x")
221 250
 puts l.make_circle(3, 6)
222  
-puts l.circular?
  251
+#puts l.circular?
  252
+puts l.min
  253
+puts l.max
223 254
 ##puts l.remove_duplicates
224 255
 ##puts l.remove_duplicates_without_buffer
225 256
 #puts l

0 notes on commit 25dc370

Please sign in to comment.
Something went wrong with that request. Please try again.