如何解决C ++链表:节点创建功能
因此,我正在学习C ++和数据结构。我想做的第一个是单链接列表。我创建/复制了以下代码:
?- from_to_distance(From,To,distance),write(from_to_distance(From,distance)),nl,fail.
from_to_distance(3,2,1)
from_to_distance(3,1,5)
from_to_distance(1,-1)
from_to_distance(2,4,4)
from_to_distance(1,0)
from_to_distance(4,3,1)
from_to_distance(4,3)
from_to_distance(2,2)
from_to_distance(4,-1)
from_to_distance(3,2)
from_to_distance(3,0)
from_to_distance(2,-2)
from_to_distance(1,0)
false.
我正在努力可视化这两行:
class Node {
public:
int data;
Node* next;
};
Node* head = NULL;
void createnode(int* value) {
Node* new_node = new Node(); //allocate memory size of node
new_node->data = *value; //data is given
new_node->next = head; //*next pointer is to head
head = new_node;
}
void printlist(Node* n) {
while (n != NULL) {
cout << n->data << "\n";
n = n->next;
}
}
在新节点中,将“下一个”节点指针设置为链接列表的“头”,这很好(我正在可视化插入在“头”左侧的节点,并将所有内容移至右边,包括这个“头部”对象)。然后,在下一行中,将head设置为“ new_node”。
那么,它创建了某种周期性连接吗?如果您愿意,此链接列表的“头部”不应该充当蛇的头部,将值添加到后面,则增加蛇的长度。
解决方法
假设您有一个序列:
a -> b -> c -> NULL; // where head points to a
这些行的作用是(假设您要将'd'添加到上一个列表中):
d -> a; // where a still points to wherever it used to point
,然后更新到HEAD应该指向的位置,它不再是具有 a 的节点,而是具有 d
的节点。版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。