2017-04-22 138 views
0

我想實現R中下面的算法:給定一個列表R:遍歷目錄

Iterate(Cell: top) 
    While (top != null) 
     Print top.Value 
     top = top.Next 
    End While 
End Iterate 

基本上,算法應儘快打破,因爲它擊中「空」甚至當列表不過度。

myls<-list('africa','america south','asia','antarctica','australasia',NULL,'europe','america north') 

我不得不添加一個for循環使用is.null()函數,但下面的代碼是災難,我需要你的幫助來解決它。

Cell <- function(top) { 
    #This algorithm examines every cell in the linked list, so if the list contains N cells, 
    #it has run time O(N). 
    for (i in 1:length(top)){ 
    while(is.null(top[[i]]) !=TRUE){ 
     print(top) 
     top = next(top) 
    } 
    } 
} 

您可以使用運行此函數:

Cell(myls) 

回答

3

你是接近,但也沒有必要在此 建設使用for(...)

Cell <- function(top){ 
    i = 1 
    while(i <= length(top) && !is.null(top[[i]])){ 
     print(top[[i]]) 
     i = i + 1 
    } 
} 

正如你看到我添加了一個額外的條件到while循環:i <= length(top)這是爲了確保你不會超越 列表的長度的情況下有沒有空項。

但是你可以使用一個for循環使用這種結構:

Cell <- function(top){ 
    for(i in 1:length(top)){ 
     if(is.null(top[[i]])) break 
     print(top[[i]]) 
    } 
} 

或者您可以使用此代碼沒有for/while建設:

myls[1:(which(sapply(myls, is.null))[1]-1)] 
+0

第二次解決方案中的精彩放置位置。偉大的工作Johan,謝謝你分享這三個。 – Bhushan

1

檢查了這一點:它運行一個由一個用於myls中的所有值並打印它們,但是如果它遇到NULL值,它會中斷。

for (val in myls) { 
    if (is.null(val)){ 
    break 
    } 
    print(val) 
} 

如果有任何疑問,請告知我。

+0

謝謝G.arima。 – Bhushan

+0

不客氣。 –