链表:头部插入一个节点

#include 
#include 

struct Node
{
	int data; 
	struct Node* next;
};
struct Node* head;//全局变量,创建一个头节点

void Insert(int x)
{
	//创建一个新的temp节点,c语言中可用malloc函数创建新节点
	struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
	temp->data = x;//把要插入的数据赋给temp节点的data
	temp->next = head;//将原本head指向的节点地址连接到新创建的节点temp
	head = temp;//然后head节点连接新创建的temp节点
}

void PrintList()
{
	//先用一个临时变量保存head,因为我们不能改变head头节点,否则会失去对第一个节点的引用
	struct Node* temp = head;//temp节点设置为头节点地址
	printf("List is:");
	//遍历这个链表
	while(temp != NULL)
	{
		printf("%d ", temp->data);//首先打印的是新插入的节点(第一个节点)
		temp = temp->next;//此时temp节点指向的是除了头节点head的第一个节点
		//在打印完第一个节点的data后,temp往后走,依次打印后面的节点的data
	}
	printf("\n");
}

int main()
{
	head = NULL;// empty list
	int n, x, i;
	printf("how many numbers?\n");//插入多少个数
	scanf("%d", &n);
	for(i = 0; i < n; i++)
	{
		printf("enter the number:\n");
		scanf("%d", &x);
		Insert(x);
		PrintList();
	}
	return 0;
}	

链表:头部插入一个节点_第1张图片

你可能感兴趣的:(链表,数据结构)