1.链表头插法
#include<stdio.h>
#include<stdlib.h>
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).data=x;
temp->next = head;
head = temp;
}
void Print() {
struct Node* temp = head;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
}
int main() {
head = NULL;
printf("How many numbers?");
int n,i,x;
scanf_s("%d", &n);
for (i = 0;i < n;i++) {
printf("Enter the number:\n");
scanf_s("%d", &x);
Insert(x);
Print();
}
}
Insert函数中出现了以下几个指针:
head,temp
head:单独一个指针,指向整个链表。
struct Node* head;
temp:一个节点,需要分配内存。
Node* temp = (Node*)malloc(sizeof(struct Node));
接下来是指向问题:
先把插入节点插上后继,在用头指针指向该节点。head用于记录开头位置。
插上后继其实分为两种情况:
head直接指向NULL
temp->next=NULL;
head=temp;
head指向数据结点
while(temp){
head=temp;
}
总结:主要是两指真初始化的部分,为什么定义方式不一样,一开始没有搞懂,导致后面在指向的时候也会产生疑惑。
本文介绍了链表的头插法插入节点的实现过程,详细讲解了如何通过`Insert`函数动态创建链表。在头插法中,`head`指针用于记录链表的起始位置,而`temp`临时指针用于新节点的创建和插入。当链表为空时,`head`直接指向新节点;否则,更新`head`使其指向新插入的节点。文章帮助读者理解链表操作中指针的使用和初始化差异。

被折叠的 条评论
为什么被折叠?



