Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ################# QUEUE IMPLEMENTATION USING R5 ###################################
- nodebase <- setRefClass("NodeBase", fields = list(value="list"))
- node <- setRefClass("Node", contains = 'NodeBase',fields = list(nextnode="NodeBase"))
- linkedList <- setRefClass("LinkedList", fields = list(head="Node",tail="Node", count="numeric"))
- createLinkedList <- function(){
- headNode <- new("Node",value=list())
- headNode$nextnode <- headNode
- linkedList <- new("LinkedList",head=headNode,tail=headNode,count=0)
- return(linkedList)
- }
- isEmpty <- function(linkedList){
- return(linkedList$count == 0)
- }
- append <- function(linkedList,item){
- # create the new node
- n <- new("Node",value=list(item),nextnode=linkedList$head)
- linkedList$tail$nextnode <- n
- linkedList$tail <- n
- linkedList$count <- linkedList$count+1
- invisible(linkedList)
- }
- removeFirstItem <- function(linkedList){
- if(isEmpty(linkedList))
- stop("Cannot remove elements from an empty list")
- val <- linkedList$head$nextnode$value[[1]]
- nextNextNode <- linkedList$head$nextnode$nextnode
- linkedList$head$nextnode <- nextNextNode
- linkedList$count <- linkedList$count-1
- if(linkedList$count == 0)
- linkedList$tail <- linkedList$head
- return(val)
- }
- toItemsList <- function(linkedList){
- l <- vector(mode="list",length=linkedList$count)
- curr <- linkedList$head$nextnode
- if(linkedList$count > 0){
- for(i in 1:linkedList$count){
- l[[i]] <- curr$value[[1]]
- curr <- curr$nextnode
- }
- }
- return(l)
- }
- # override length and print method
- lengthMethod <- setMethod("length", signature(x="LinkedList"), function(x){x$count})
- showmethod <- setMethod("show", signature(object="LinkedList"), function(object){print(paste("LinkedList with ", object$count, " elements"))})
- ###############################################################################
- ###### USAGE EXAMPLE ######
- queue = createLinkedList()
- append(queue,1)
- append(queue,2)
- append(queue,3)
- toItemsList(queue)
- print(queue)
- removeFirstItem(queue)
- removeFirstItem(queue)
- removeFirstItem(queue)
- isEmpty(queue)
- length(queue)
- ##########################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement