链表C插入函数

链表C插入函数,c,pointers,linked-list,C,Pointers,Linked List,我明天要考试数据结构,我想弄清楚这段代码中的插入函数。请您在函数Insert中向我解释一下为什么temp->next=head #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* head; void Insert(int x) { struct Node *temp = (struct Node

我明天要考试数据结构,我想弄清楚这段代码中的插入函数。请您在函数
Insert
中向我解释一下为什么
temp->next=head

#include <stdio.h>
#include <stdlib.h>

struct Node {

    int data;
    struct Node* next;
};

struct Node* head;

void Insert(int x) {

    struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = x;
    temp->next = NULL;
    if(head != NULL) { temp->next = head;}
    head = temp;


}

void Print() {

    struct Node* temp = head;
    printf("List is: ");

    while(temp != NULL) {

        printf(" %d",temp->data);
        temp = temp->next;

    }
    printf("\n");

}


int main() {

     head = NULL;

     Insert(1);
     Insert(2);
     Insert(3);
     Insert(4);
     Insert(5);

     Print();



    return 0;
}
#包括
#包括
结构节点{
int数据;
结构节点*下一步;
};
结构节点*头部;
空白插入(整数x){
结构节点*temp=(结构节点*)malloc(sizeof(结构节点));
温度->数据=x;
temp->next=NULL;
如果(head!=NULL){temp->next=head;}
压头=温度;
}
作废打印(){
结构节点*温度=头部;
printf(“列表为:”);
while(temp!=NULL){
printf(“%d”,临时->数据);
温度=温度->下一步;
}
printf(“\n”);
}
int main(){
head=NULL;
插入(1);
插入(2);
插入(3);
插入(4);
插入(5);
打印();
返回0;
}
让我们看一个例子:-

insert(1);
将创建新节点并将其数据字段设置为1。然后检查head是否为NULL。是的,因为这是我们插入的第一个元素。所以它使头指向这个元素。这意味着在这之后

head -> 1
现在你知道了

insert(2);
在同一行上,它将创建节点以容纳2。接下来检查head是否为NULL。情况并非如此

temp->next = head;
意味着下一个临时节点(2)将指向头部(现在是1)。在此声明之后

2 -> 1 (head)
然后你执行

head = temp;
这将使头部指向2(新创建的节点)


通过这种方式,您将继续添加元素,并使头指针指向添加到列表中的最新元素。这将有助于您以后使用头指针遍历列表。

您可以通过替换头在列表前面插入新节点。新头将是新分配的节点
temp
,旧头将是列表中的第二个节点,因此
temp->next

用铅笔和纸可以很容易地想出这样的概念。或者对于ASCII草图,其中
->
表示通过
下一个
指针的链接,
|
表示指向非节点链接的节点的直接指针:

head
 | 
 3 -> 2 -> 1 -> NULL
在插入4之后,但在分配新磁头之前:

temp head
 |    |
 4 -> 3 -> 2 -> 1 -> NULL
head 
 |   
 4 -> 3 -> 2 -> 1 -> NULL
分配新的头后:

temp head
 |    |
 4 -> 3 -> 2 -> 1 -> NULL
head 
 |   
 4 -> 3 -> 2 -> 1 -> NULL
现在,您有了一个合适的列表,可以通过
head
next
指针访问所有添加的节点。如果没有重新命名
头部
,则只能访问旧节点


这也适用于
head==NULL
的空列表,除非您无法访问
head->next

在linkedlist中添加新元素后会发生这种情况。添加新元素时,必须使新元素成为标题,因此必须指向上一个标题作为链接列表中的下一项

根据您的评论-


“但当我们删除此部分时,为什么程序不起作用?是吗 保留旧打印头的地址列表

不,不是。因为这里

if(head != NULL) { temp->next = head;}
head = temp;
…我们看到如果我们删除
head=temp;
您将孤立您的列表,因为如果
head==NULL
它仍然是
NULL
。如果不是,您没有指向
temp
的链接,因此您将孤立
temp
和所有其他
insert
s


如果(head!=NULL){temp->next=head;}
语句确保,如果您确实有一个,您的列表将附加到新的
,但没有
head=temp;
语句则无关紧要。

旧的
head
将成为
temp->next
temp
将成为新的
指针。为简单起见,除非它是一个有序的列表,否则您应该ld总是在头部插入,这就是它的作用。但为什么我们删除这部分时程序不起作用?是保留旧头部的地址来打印列表吗?@ChiefTwoPencils你在开玩笑吗?@AliAmiri,关于哪部分?