C 中的链表
我在使用双链表时遇到问题:我无法通过另一个节点从节点获取数据。这样:节点->上一个->上一个。但是node->prev就可以了。 有人知道为什么吗?
代码:
/*Add value - right side*/
void addListRight(doubleList *node, int value)
{
doubleList *newNode;
newNode = createList();
newNode->val = value;
newNode->right = node->right;
newNode->left = node;
node->right->left = newNode; /*<-Error start here - 'segmentation error' or something like this*/
node->right = newNode;
}
用Google,我发现有些人把()这样写:(node->right)->right。我尝试过但结果是一样的。
使用 GCC/Ubuntu 10.10
*我想说“->”的正确词但我不知道英文。我的错..对不起!这个问题的标签也是如此!
I'm having problem with double linked lists: I can't get data from nodes throgh another node. This way: node->prev->prev. But node->prev is fine.
Anyone knows why?
The code:
/*Add value - right side*/
void addListRight(doubleList *node, int value)
{
doubleList *newNode;
newNode = createList();
newNode->val = value;
newNode->right = node->right;
newNode->left = node;
node->right->left = newNode; /*<-Error start here - 'segmentation error' or something like this*/
node->right = newNode;
}
Using Google, I found that some guys put () like this: (node->right)->right. I tryed it but the result is the same.
Using GCC/Ubuntu 10.10
*I would like to say the proprer word for '->' but I don't know it in English. My bad.. sorry! Same about the tags of this question!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在使用这样的指针之前应该检查 NULL。列表的开头不会有上一个。
You should check for NULL before using a pointer like that. There will be no prev at the head of the list.
您似乎收到了分段错误错误。这意味着您正在尝试访问无效内存。我的猜测是你还没有分配
node->right
或者它是NULL。确保所有指针均有效且已正确分配。作为参考,下面是一个链表实现示例:
It looks like you're getting a segmentation fault error. This means you are trying to access invalid memory. My guess is that you haven't allocated
node->right
or it's NULL. Make sure all your pointers are valid and have been allocated properly.For reference, here is an example linked list implementation: