implement stack using linked list in ruby

Ruby program for implement stack using linked list. Here problem description and other solutions.

#  Ruby program for
#  Implementation stack using linked list

#  Stack Node
class StackNode 
	# Define the accessor and reader of class StackNode
	attr_reader :data, :next
	attr_accessor :data, :next
	def initialize(data, top) 
		self.data = data
		self.next = top
	end
end

class MyStack 
	# Define the accessor and reader of class MyStack
	attr_reader :top, :count
	attr_accessor :top, :count
	def initialize() 
		self.top = nil
		self.count = 0
	end

	#  Returns the number of element in stack
	def size() 
		return self.count
	end

	def isEmpty() 
		if (self.size() > 0) 
			return false
		else
 
			return true
		end

	end

	#  Add a new element in stack
	def push(data) 
		#  Make a new stack node
		#  And set as top
		self.top = StackNode.new(data, self.top)
		#  Increase node value
		self.count += 1
	end

	#  Add a top element in stack
	def pop() 
		temp = 0
		if (self.isEmpty() == false) 
			#  Get remove top value
			temp = self.top.data
			self.top = self.top.next
			#  Reduce size
			self.count -= 1
		end

		return temp
	end

	#  Used to get top element of stack
	def peek() 
		if (!self.isEmpty()) 
			return self.top.data
		else
 
			return 0
		end

	end

end

class Test end

def main() 
	#  Create new stack 
	s = MyStack.new()
	print("\n Is empty : ", s.isEmpty(), "\n")
	#  Add element
	s.push(15)
	s.push(14)
	s.push(31)
	s.push(21)
	s.push(10)
	print("\n Top  : ", s.peek(), "\n")
	print(" Size : ", s.size(), "\n")
	print("\n Is empty : ", s.isEmpty(), "\n")
	#  Delete Stack Element
	data = s.pop()
	print("\n Pop element ", data, "\n")
	print(" Size : ", s.size(), "\n")
	data = s.pop()
	print("\n Pop element ", data, "\n")
	print(" Size : ", s.size(), "\n")
end

main()

Output

 Is empty : true

 Top  : 10
 Size : 5

 Is empty : false

 Pop element 10
 Size : 4

 Pop element 21
 Size : 3


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







© 2021, kalkicode.com, All rights reserved