C++函数中链表的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3928935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:04:54  来源:igfitidea点击:

size of linked list in c++ function

c++linked-list

提问by Salar

Can someone please tell what is the code for checking the size of a linked list(number of nodes).This is what my code is(inserting nd deleting head + printing info of all nodes)

有人可以告诉我检查链表大小的代码是什么(节点数)。这就是我的代码(插入 nd 删除头 + 打印所有节点的信息)

struct node 
{
    int info;
    node *nextptr;
};

class list
{
private:
    node *L,*tail;
     int count;

public:
    list()
    {
        L=tail=NULL;
        count=0;
    }

    void InsertHead(int info);
    int RemoveHead();
    void Print();
}; 

回答by SingleNegationElimination

There are two ways to manage the size of a linked list, both have shortcomings. The simplest is to manage a count variable, your class has such a variable, and you increment it every time you add a node to the list, and decrement it every time you remove a node.

管理链表大小的方法有两种,都有缺点。最简单的就是管理一个count变量,你的类有这样一个变量,你每次往链表中添加一个节点就递增它,每次删除一个节点就递减它。

In this case, you can get the size of the linked list in constant time. The downside is that a useful operation, splice, where you take a list and cut it into two smaller lists somewhere in the middle, becomes linear complexity, because now you have to count how many nodes are in the sublists.

在这种情况下,您可以在恒定时间内获取链表的大小。缺点是一个有用的操作,拼接,你把一个列表切成中间的两个更小的列表,变成了线性复杂度,因为现在你必须计算子列表中有多少节点。

If you want splice to be constant, then you can't track the size of the lists. So any time you want to get the size of the list, you have to count how many nodes are there.

如果您希望 splice 保持不变,则无法跟踪列表的大小。所以任何时候你想得到列表的大小,你必须计算有多少个节点。

回答by AndersK

Well the simplest would beto add in the function InsertHead add ++count and in the RemoveHead do --count

那么最简单的方法是在函数 InsertHead add ++count 和 RemoveHead do --count 中添加

Otherwise you could use a loop to go through the list

否则,您可以使用循环来遍历列表

e.g.

例如

node* p = L; 
while (p != NULL) 
{ 
  ++count; 
  p = p->nextptr; 
}

回答by dutt

You need to create a counter and then loop through your list increasing the counter

您需要创建一个计数器,然后遍历您的列表增加计数器

pseudocode:

伪代码:

count = 0
iterator = head
while(iterator != 0)
    count++
    iterator = iterator.next

回答by Greg Domjan

Try this:

尝试这个:

int size() { return count; }

回答by Andrew Cooper

Something like:

就像是:

int Count()
{
    return count;
}