From 2ab1f330b42ccfdd14bb35c0ee11334ad413ec51 Mon Sep 17 00:00:00 2001 From: Harsh kumar Date: Sat, 5 Oct 2019 11:46:16 +0530 Subject: [PATCH] Create CircularList --- data_structures/LinkedLists/CircularList.rb | 93 +++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 data_structures/LinkedLists/CircularList.rb diff --git a/data_structures/LinkedLists/CircularList.rb b/data_structures/LinkedLists/CircularList.rb new file mode 100644 index 0000000..62636c1 --- /dev/null +++ b/data_structures/LinkedLists/CircularList.rb @@ -0,0 +1,93 @@ +#Define a node for the list +class Node + attr_accessor :value, :next + def initialize(value) + @value = value + @next = nil + end +end + +# Class for circular linked list (last node points to the head node) +class CircularList + attr_accessor :head + + def initialize() + @head = nil + end + + def insert_end(value) + newNode = Node.new(value) + if (@head == nil) + @head = newNode + @head.next = @head + else + tempNode = @head + while (tempNode.next != @head) + tempNode = tempNode.next + end + newNode.next = @head + tempNode.next = newNode + end + end + + def insert_head(value) + newNode = Node.new(value) + if (@head == nil) + @head = newNode + @head.next = head + else + tempNode = @head + while (tempNode.next != @head) + tempNode = tempNode.next + end + newNode.next = @head + tempNode.next = newNode + @head = newNode + end + end + + def print_list + print "[" + if (@head != nil) + printNode = @head + while (printNode.next != @head) + print "#{printNode.value}" + print ", " + printNode = printNode.next + end + print printNode.value + end + print "]" + STDOUT.flush + end + + def delete_head + if (@head != nil) && (@head.next != @head) + newHead = @head.next + tempNode = newHead + while(tempNode.next != @head) + tempNode = tempNode.next + end + tempNode.next = newHead + @head = newHead + elsif (@head != nil) && (@head.next == @head) + @head = nil + end + end + + def delete_end + if (@head != nil) && (@head.next != @head) + tempNode = @head + while (tempNode.next.next != @head) + tempNode = tempNode.next + end + tempNode.next = @head + elsif (@head != nil) && (@head.next == @head) + @head = nil + end + end + + def isEmpty() + return (@head==nil) + end +end \ No newline at end of file