implement queue using linked list in ruby
Ruby program for implement queue using linked list. Here more information.
# Ruby Program for
# Implement queue using linked list
# Create Q node
class QNode
# Define the accessor and reader of class QNode
attr_reader :data, :next
attr_accessor :data, :next
def initialize(value)
self.data = value
self.next = nil
end
end
class MyQueue
# Define the accessor and reader of class MyQueue
attr_reader :head, :tail, :count
attr_accessor :head, :tail, :count
def initialize()
self.head = nil
self.tail = nil
self.count = 0
end
def size()
return self.count
end
def isEmpty()
return self.count == 0
end
# Add new node of queue
def enqueue(value)
# Create a new node
node = QNode.new(value)
if (self.head == nil)
# Add first element into queue
self.head = node
else
# Add node at the end using tail
self.tail.next = node
end
self.count += 1
self.tail = node
end
# Delete a element into queue
def dequeue()
if (self.head == nil)
print("Empty Queue\n")
return -1
end
# Pointer variable which are storing
# the address of deleted node
temp = self.head
# Visit next node
self.head = self.head.next
self.count -= 1
if (self.head == nil)
# When deleting a last node of linked list
self.tail = nil
end
return temp.data
end
# Get front node
def peek()
if (self.head == nil)
print("Empty Queue\n")
return -1
end
return self.head.data
end
end
def main()
task = MyQueue.new()
# Initially number of element
print("isEmpty : ", task.isEmpty(), "\n")
# Add element into queue
task.enqueue(10)
task.enqueue(20)
task.enqueue(30)
task.enqueue(40)
task.enqueue(50)
# Test other function
print("size : ", task.size(), "\n")
print("peek : ", task.peek(), "\n")
print("dequeue : ", task.dequeue(), "\n")
print("size : ", task.size(), "\n")
print("peek : ", task.peek(), "\n")
print("isEmpty : ", task.isEmpty(), "\n")
end
main()
Output
isEmpty : true
size : 5
peek : 10
dequeue : 10
size : 4
peek : 20
isEmpty : false
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment