class LinkedList::Singly

Public Class Methods

new(data = nil) click to toggle source
# File lib/linked_list_sourav.rb, line 37
def initialize(data = nil) # constructor
  @count = 1
  if data.class == Array
    @head = Node.new(data[0])
    data.each.with_index { |datum, index| self.add(datum) if index > 0}
  else
    @head = Node.new(data)
  end
  self
end

Public Instance Methods

add(data) click to toggle source
# File lib/linked_list_sourav.rb, line 72
def add(data)  # adds new members
  node = @head
  while (node.forward != nil)
    node = node.forward
  end
  node.forward = Node.new(data)
  @count += 1
  node.forward
end
add_a(data) click to toggle source
# File lib/linked_list_sourav.rb, line 82
def add_a(data) # adds array members to the list
  node = @head
  while (node.forward != nil)
    node = node.forward
  end
  if data.respond_to? :each
    data.each { |datum| self.add(datum)}
  end
  self
end
delete(data) click to toggle source
# File lib/linked_list_sourav.rb, line 121
def delete(data) # deletes a single member
  node = @head
  deleted_node = ''
  if node.data === data
    @head = node.forward
    deleted_node = node
    @count -= 1
  else
    node = @head
    while( node != nil && node.forward != nil && (node.forward).data != data)
      node = node.forward
    end
    if (node != nil) && (node.forward != nil)
      node.forward = (node.forward).forward
      @count -= 1
    end
    deleted_node = node.forward
  end
  deleted_node = nil
end
edit(old_data, new_data) click to toggle source
# File lib/linked_list_sourav.rb, line 93
def edit(old_data, new_data)
  node = find(old_data)
  if node
    node.data = new_data
  end
end
find(data) click to toggle source
# File lib/linked_list_sourav.rb, line 60
def find(data)
  node = @head
  while (node != nil && node.data != data )
    node = node.forward
  end
  node
end
head() click to toggle source
# File lib/linked_list_sourav.rb, line 48
def head #returns head
  @head
end
no_of_nodes() click to toggle source
# File lib/linked_list_sourav.rb, line 68
def no_of_nodes
  @count
end
parse() click to toggle source
# File lib/linked_list_sourav.rb, line 52
def parse # parses all the members
  node = @head
  while (node != nil)
    puts node.data
    node = node.forward
  end
end
to_a() click to toggle source
# File lib/linked_list_sourav.rb, line 100
def to_a # returns an array of all data
  node = @head
  array = Array.new
  while (node != nil)
    array << node.data
    node = node.forward
  end
  array
end
to_s() click to toggle source
# File lib/linked_list_sourav.rb, line 110
def to_s # returns all data in form of string
  node = @head
  string = String.new(@head.data.to_s)
  node = node.forward
  while (node != nil)
    string << ", " << node.data.to_s
    node = node.forward
  end
  string
end