簡體   English   中英

如何計算雙向鏈表中的元素數?

[英]How to count number of elements in a doubly-linked list?

列表的布局方式如下:

struct Node {
    Node *next;
    Node *prev;
    T datum;
};

Node *first;   // points to first Node in list, or 0 if list is empty  
Node *last;    // points to last Node in list, or 0 if list is empty

我努力了:

int i =0;  
while(first->next)
{  
    i++;  
}  

但這似乎不對。

您的函數需要在列表上循環,同時更新指向當前節點的指針。 像這樣的東西:

function getLen(head) {
    var curNode = head;
    var len = 0;

    while (curNode)
        len++;
        curNode = curNode.next;
    }
    return len;
}

您可以通過在節點之間移動指針直到指針為NULL來解決此問題。 計算指針為非NULL的次數。 所需的代碼非常簡單:

int list_size(const Node *ptr)
{
    int size = 0;
    while (ptr) {
        size++;
        ptr = ptr->next;
    }
    return size;
}

像這樣使用它:

int size = list_size(first);

此代碼不使用prev指針,因此也適用於單鏈接列表。

嘗試這個。

int i=0;
if(first!=0){
    ++i;
    while(first!=last){
        first=first->next;
        ++i;
    }
}
std::cout<<i<<std::endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM