运行情况:
//头部插入一个节点
#include <stdlib.h>
#include <stdio.h>
struct Node {
int data;
struct Node* next; //这是指向Node的指针,将存储下一个Node的地址
//C语言:struct Node* next;
//C++: Node* next;
};
struct Node* head;//指向Node的指针Node* (全局变量)
void Insert(int x){
Node* temp=(Node*)malloc(sizeof(struct Node));//创建节点
/*malloc返回指向起始地址的指针
因为malloc返回一个void指针,所以使用(Node*)强制转换 */
//temp是指针变量 我们解引用指针变量以修改此特定节点上的值
temp->data =x;
temp->next =head;//涵盖了 链表为空和非空 这两种情况
head = temp;
/*相当于 temp->data =x;
temp->next =NULL;
if(head!=NULL)temp->next=head;
head = temp; */
}
void Print(){
struct Node* temp=head;
/*创建一个局部变量 名为temp的指向Node的指针
为什么要用局部变量 因为我们不能修改链表表头
否则我们会失去对第一个节点的引用 */
printf("list is:");
//遍历链表的循环
while(temp !=NULL){//temp非空时
printf(" %d",temp->data ); //每次打印该节点的值
temp=temp->next ;//修改局部变量的地址 转到下一个节点
}
printf("\n");
}
int main(){
head = NULL;//指针不指向任何地方->链表是空的
printf("how many numbers?\n");
int n,i,x;
scanf("%d",&n);
for(int i=0;i<n;i++){
printf("enter the number \n");
scanf("%d",&x);
Insert(x);//调用插入函数Insert
Print(); //调用Print函数来打印链表中所有节点的值
}
}