Permalink
Browse files

find min/max in O(1) time

  • Loading branch information...
1 parent cb3171c commit 25dc3706e20cff066ff181a33ef6552ad0ae8913 @anjshenoy committed Apr 20, 2012
Showing with 36 additions and 5 deletions.
  1. +36 −5 linked_list.rb
View
@@ -1,9 +1,10 @@
class LinkedList
- attr_accessor :head, :last
+ attr_accessor :head, :last, :min, :max
def initialize
self.head = Node.new
+ self.min = self.max = nil
end
def add_to_head(data)
@@ -29,10 +30,31 @@ def add_to_tail(data)
self.last.next = n
self.last = n
end
+ update_min_max(n)
self
end
alias_method :enqueue, :add_to_tail
+ def update_min_max(node)
+ update_min(node)
+ update_max(node)
+ end
+ private :update_min_max
+
+ def update_max(node)
+ if self.max.nil? || (node > self.max)
+ self.max = node
+ end
+ end
+ private :update_max
+
+ def update_min(node)
+ if self.min.nil? || (node < self.min)
+ self.min = node
+ end
+ end
+ private :update_min
+
def drop_last
n = self.head
until (n.next == self.last)
@@ -186,7 +208,6 @@ def make_circle(start_position=1, end_position=self.size)
puts self
self
end
-
end
class Node
@@ -201,12 +222,20 @@ def to_s
end
def ===(other)
- self.data = other.data
+ self.data == other.data
end
def +(another_node)
self.data + another_node.data
end
+
+ def >(another_node)
+ self.data > another_node.data
+ end
+
+ def <(another_node)
+ self.data < another_node.data
+ end
end
##stack
@@ -215,11 +244,13 @@ def +(another_node)
#puts l.pop
#puts l
l = LinkedList.new
-l.enqueue("a").enqueue("x").enqueue("c")
+l.enqueue("z").enqueue("x").enqueue("c")
#l.dequeue
l.enqueue("a").enqueue("b").enqueue("x")
puts l.make_circle(3, 6)
-puts l.circular?
+#puts l.circular?
+puts l.min
+puts l.max
##puts l.remove_duplicates
##puts l.remove_duplicates_without_buffer
#puts l

0 comments on commit 25dc370

Please sign in to comment.