Advertisement
digemall

Queue structure (as Linked List) in R using R5 classes

Sep 25th, 2012
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.16 KB | None | 0 0
  1. ################# QUEUE IMPLEMENTATION USING R5 ###################################
  2. nodebase <- setRefClass("NodeBase", fields = list(value="list"))
  3. node <- setRefClass("Node", contains = 'NodeBase',fields = list(nextnode="NodeBase"))
  4. linkedList <- setRefClass("LinkedList", fields = list(head="Node",tail="Node", count="numeric"))
  5.  
  6. createLinkedList <- function(){
  7.   headNode <- new("Node",value=list())
  8.   headNode$nextnode <- headNode
  9.  
  10.   linkedList <- new("LinkedList",head=headNode,tail=headNode,count=0)
  11.   return(linkedList)
  12. }
  13.  
  14. isEmpty <- function(linkedList){
  15.   return(linkedList$count == 0)
  16. }
  17.  
  18. append <- function(linkedList,item){
  19.  
  20.   # create the new node
  21.   n <- new("Node",value=list(item),nextnode=linkedList$head)
  22.  
  23.   linkedList$tail$nextnode <- n
  24.   linkedList$tail <- n
  25.  
  26.   linkedList$count <- linkedList$count+1
  27.  
  28.   invisible(linkedList)
  29. }
  30.  
  31. removeFirstItem <- function(linkedList){
  32.   if(isEmpty(linkedList))
  33.     stop("Cannot remove elements from an empty list")
  34.   val <- linkedList$head$nextnode$value[[1]]
  35.  
  36.   nextNextNode <- linkedList$head$nextnode$nextnode
  37.   linkedList$head$nextnode <- nextNextNode
  38.  
  39.   linkedList$count <- linkedList$count-1
  40.   if(linkedList$count == 0)
  41.     linkedList$tail <- linkedList$head
  42.   return(val)
  43. }
  44.  
  45. toItemsList <- function(linkedList){
  46.   l <- vector(mode="list",length=linkedList$count)
  47.   curr <- linkedList$head$nextnode
  48.   if(linkedList$count > 0){
  49.     for(i in 1:linkedList$count){
  50.       l[[i]] <- curr$value[[1]]
  51.       curr <- curr$nextnode
  52.     }
  53.   }
  54.   return(l)
  55. }
  56.  
  57. # override length and print method
  58. lengthMethod <- setMethod("length", signature(x="LinkedList"), function(x){x$count})
  59. showmethod <- setMethod("show", signature(object="LinkedList"), function(object){print(paste("LinkedList with ", object$count, " elements"))})
  60. ###############################################################################
  61.  
  62. ###### USAGE EXAMPLE ######
  63.  
  64. queue = createLinkedList()
  65.  
  66. append(queue,1)
  67. append(queue,2)
  68. append(queue,3)
  69.  
  70. toItemsList(queue)
  71.  
  72. print(queue)
  73.  
  74. removeFirstItem(queue)
  75. removeFirstItem(queue)
  76. removeFirstItem(queue)
  77.  
  78. isEmpty(queue)
  79.  
  80. length(queue)
  81.  
  82.  
  83. ##########################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement