How to implement the linked-list process using class concepts in systemverilog!

Thanks a lot Dave for the clarification and idea. I just tried appending some more code this for adding node at the end and inserting node in-between.


module link_list;
 
class node_class;
 int la;
 static int node_count=0;

 node_class next;
   virtual function void print_node;
      $write(la," ");
   endfunction
   virtual function void print_list();
      print_node();
      if (next != null)
	next.print_list();
      else
	$write("\n");
   endfunction
   
   virtual function void insert_node(int val);
      node_class node = new;
      node.la = val;
      node.next = next;
      next = node;
      node_count++;
   endfunction : insert_node

   virtual function void insert_node_end(int val);
     node_class tmp;
     
     node_class node = new;
     node.la = val;

     tmp = next;

     if (tmp == null) begin
      node.next = next;
      next = node;
     end 
     else begin
      while (tmp.next != null) begin
       tmp = tmp.next;
      end
      node.next = tmp.next;
      tmp.next = node;
     end
     node_count++;
   endfunction: insert_node_end

   virtual function void insert_node_index(int index, int val);
     int node_count_tmp=1;
     node_class tmp;

     node_class node = new;
     node.la = val;

     tmp = next;
  
     if (index > node_count) $write("Index %0d Is Beyound Node Count. Insert Proper Index Value\n", index);
     else begin
       while (node_count_tmp != index) begin
         node_count_tmp++;
         tmp = tmp.next;
       end
       node.next = tmp.next;
       tmp.next = node;
     end
   endfunction: insert_node_index 

endclass: node_class 
 
initial begin
  node_class head;
   head = new();
   head.la = 0;
   head.print_list();
   head.insert_node(10);
   head.print_list();
   head.insert_node(20);
   head.print_list();
   head.next.insert_node(30);
   head.print_list();
   head.insert_node_end(40);
   head.print_list();

   head.insert_node_index(1, 50); 
   head.print_list();
end
 
endmodule: link_list

1 Like