[英]trying to understand this linkedlist insertion code
我有這個代碼
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;
}
我正在觀看此視頻 ,看起來代碼可以正常工作。 我很難把它放在一起。
我們有一個節點頭,它在main方法中最初設置為NULL。
鏈表包含一個int和next。 此插入代碼將數據設置為int並位於head旁邊。 然后將其設置為溫度。
因為我們將temp.next設置為head,然后head = temp,這是否會使head的int值一遍又一遍地指向自身?
到目前為止,我只對鏈表進行了迭代,最后一個是NULL。
此代碼在鏈接列表的開頭插入一個項目-它創建一個新節點,設置其數據,並使其next
指向當前head
。
沒有。
node* temp = malloc(sizeof(struct node));
temp->data = x;
我們有一個新節點,並設置了它的值。
temp->next = head;
head
(如果有)將在列表中此元素之后 。 這意味着這應該成為我們的新head
。
head = temp;
現在是。
如果head
為NULL
,則此列表沒有預期的next
條目。
如果head
不為NULL
,則此節點為新的head,其next
指向列表中的第二個元素(舊的head
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.