0
点赞
收藏
分享

微信扫一扫

STM32作业实现(一)串口通信

上古神龙 2024-06-02 阅读 7

Linked List

Inserting a node at beginning

#include<stdlib.h>//为了用malloc
#include<stdio.h>
struct node {
	int data;
	struct node* next;
	 //在cpp中可以只写 Node *Link;
    //为了表意明确,Link也经常被命名为next
};
struct node* head;

//核心代码
//头插法 Linked List 
void insert(int x)
{
	node* temp = (node*)malloc(sizeof(struct node));
	//Cpp中可以 Node *temp=new Node();
	if (temp == NULL) 
    {
     printf("Memory allocation failed!\n");
    return;
    }
	temp->data = x;//创建待插入的结点
	//(*temp).data=x;
	temp->next = head;//该节点在链表不为空时,指向上一个head指向的结点。
	//链表为空时,指向零,刚好head此时为0
	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(2);
	print();
	insert(100);
	insert(99);
	print();
	return 0;
}







举报

相关推荐

0 条评论