【发布时间】:2015-04-20 15:08:53
【问题描述】:
在尝试理解链表时,我遇到过这种或类似的方式来构建链表:
typedef struct node{
int data;
node *next;
}node;
node* init(int a[], int n){
node *head, *p;
for(int i=0; i<n; ++i){
node *nd = new node();
nd->data = a[i];
if(i==0){
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
但是为什么要使用它而不是 std::list<..> 呢?
【问题讨论】:
-
为什么这个 typedef 也是一个名为 'node' 的结构的 'node'?
-
我投票结束这个问题,因为没有“正确”的答案。我猜想实现单链表而不是使用
std::list作为练习很有用,并理解为什么std::list上的某些算法复杂性(例如插入是恒定的,查找是线性的)是它们的方式。typedef struct node部分看起来很像这是基于一些 C 代码。 -
在生产代码中确实没有理由。了解链表如何在后台工作通常是一种学习练习。
-
这是一个单链表,所以直接对应的是C++11
std::forward_list。std::list是一个双向链表。
标签: c++ linked-list nodes stdlist