Data structures in Ruby for beginners(Linked List)
'''author => shivamzaz @imsec
tag => simply linked list creation
level => easy but not cakewalk
'''
Node=Struct.new(:value,:next)
# optional <=>
'''class Node
attr_accessor :value , :next #value by ll and val by user function call
def initialize value, next_i
@value = value
@next = next_i
#puts "initialized with value :" + value.to_s
end
end'''
class LinkedList
def initialize value # head ( first node creation ) creation
@head= Node.new(value,nil) #=> [5,nil] initially
end
def add(value)
current = @head
while(current.next!=nil)
current=current.next
end
current.next=Node.new(value,nil)
end
def delete(value)
current=@head
if(current.value==value)
@head=@head.next
else
current=@head
while((current.next.value!=value)&& (current.next!=value) && (current!=nil)) # previous index tracking..
current=current.next
end
if(current!=nil && current.next!=nil)
current.next=current.next.next
end
end
end
def display()
current=@head
full_list=[]
while(current.next!=nil)
full_list<<current.value.to_s
current=current.next
end
full_list+=[current.value.to_s]
puts full_list.join("->")
end
end
ll=LinkedList.new(5) # first node creation.
#ll=LinkedList.add(5)
ll.add(5)
ll.add(10)
#ll.delete(10)
ll.display
-------------------------------------------------------------------------------------------------------------------------------
<<<Happy Coding>>> ->Shivam Gupta
'''author => shivamzaz @imsec
tag => simply linked list creation
level => easy but not cakewalk
'''
Node=Struct.new(:value,:next)
# optional <=>
'''class Node
attr_accessor :value , :next #value by ll and val by user function call
def initialize value, next_i
@value = value
@next = next_i
#puts "initialized with value :" + value.to_s
end
end'''
class LinkedList
def initialize value # head ( first node creation ) creation
@head= Node.new(value,nil) #=> [5,nil] initially
end
def add(value)
current = @head
while(current.next!=nil)
current=current.next
end
current.next=Node.new(value,nil)
end
def delete(value)
current=@head
if(current.value==value)
@head=@head.next
else
current=@head
while((current.next.value!=value)&& (current.next!=value) && (current!=nil)) # previous index tracking..
current=current.next
end
if(current!=nil && current.next!=nil)
current.next=current.next.next
end
end
end
def display()
current=@head
full_list=[]
while(current.next!=nil)
full_list<<current.value.to_s
current=current.next
end
full_list+=[current.value.to_s]
puts full_list.join("->")
end
end
ll=LinkedList.new(5) # first node creation.
#ll=LinkedList.add(5)
ll.add(5)
ll.add(10)
#ll.delete(10)
ll.display
-------------------------------------------------------------------------------------------------------------------------------
<<<Happy Coding>>> ->Shivam Gupta
No comments:
Post a Comment