我有这个代码
struct Node {
int data;
struct *Node next;
};
struct Node *head;
void insert(int x) {
node* temp = (node*)malloc(sizeof(struct node));
temp->data = x;
temp->next = head;
head = temp;
}
int main()
{
head = NULL;
}
我正在关注此video,看起来代码有效。虽然我很难把它组合在一起。
我们有一个节点头,在main方法中最初设置为NULL。
linkedlist 包含一个int和next。此插入代码将数据设置为int和head。然后它设定为临时。
这不会让头部成为int然后让它一遍又一遍指向自己,因为我们将temp.next设置为head然后head = temp?
到目前为止,我只对 linkedlist 进行了迭代,其中最后一个是NULL。
答案 0 :(得分:0)
此代码在链接列表的开头处插入一个项目 - 它创建一个新节点,设置其数据,并使其next
指向当前head
答案 1 :(得分:0)
没有
node* temp = malloc(sizeof(struct node));
temp->data = x;
我们有一个新节点,并设置了它的值。
temp->next = head;
head
(如果有的话)在列表中的此元素之后。这意味着这应该是我们的新head
。
head = temp;
现在是。
如果head
为NULL
,则此列表没有next
条目,正如预期的那样。
如果head
不是NULL
,则此节点是新头,其next
指向列表中的 second 元素(旧{ {1}})。