c++ 中链表的大小功能
有人可以告诉我检查链表大小(节点数)的代码是什么吗?这就是我的代码(插入和删除头+打印所有节点的信息)
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();
};
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)
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();
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有两种方法来管理链表的大小,两者都有缺点。最简单的是管理一个计数变量,你的类有这样一个变量,每次向列表中添加节点时递增它,每次删除节点时递减它。
这样的话,就可以在常数时间内得到链表的大小。缺点是,一个有用的操作(拼接),即获取一个列表并将其在中间的某个位置切成两个较小的列表,会变成线性复杂性,因为现在您必须计算子列表中有多少个节点。
如果您希望 splice 保持不变,则无法跟踪列表的大小。因此,每当您想要获取列表的大小时,您都必须计算其中有多少个节点。
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.
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.
那么最简单的方法是在函数 InsertHead add ++count 中添加,并在 RemoveHead do --count 中添加
,否则您可以使用循环来遍历列表,
例如
Well the simplest would beto add in the function InsertHead add ++count and in the RemoveHead do --count
Otherwise you could use a loop to go through the list
e.g.
您需要创建一个计数器,然后循环遍历列表,增加计数器
伪代码:
You need to create a counter and then loop through your list increasing the counter
pseudocode:
像这样的东西:
Something like:
试试这个:
Try this: