2021-5-26【单链表】【结构体】【含注释】

这篇博客展示了如何使用C语言创建一个链表,包括创建节点、在链表头部插入节点、按数据删除节点以及打印链表的元素。通过`createlist()`、`createNode()`、`insertNodeByHead()`和`deleteNodeByAppoin()`等函数,实现了基本的链表操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

struct Node{
	int data;
	struct Node *next;//结构体指针 
}; 

struct Node* createlist()//创建链表 
{
	struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));//开辟空间 
	headNode->next=NULL;//头指针指向NULL 
	return headNode;
}

struct Node* createNode(int data)//创建结点 
{
	struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
	newNode->data=data;//记录数据 
	newNode->next=NULL;//结点指针指向NULL 
	return newNode;
}

void printlist(struct Node* headNode)//打印链表 
{
	struct Node* pMove = headNode->next;//需要一个新的指针结构体移动来输出 
	while (pMove)//pMove不为空时,循环继续 
	{
		printf("%d\t",pMove->data);//输出 
		pMove = pMove->next; //指向下一个 
	}
	printf("\n");
} 

void insertNodeByHead(struct Node* headNode,int data)//插入结点 
{
	struct Node* newNode = createNode(data);//把数据存入一个结点中 
	newNode->next = headNode->next;//新结点的指针 指向 插入位置结点的指针指向的位置 
	headNode->next = newNode;	   //插入位置结点的指针 指向 新结点 
} 

void deleteNodeByAppoin(struct Node* headNode,int posData)//删除结点 (从头开始) 
{
	struct Node* posNode = headNode->next;//找到要删除的结点 
	struct Node* posNodeFront = headNode;//找到要删除的前一个结点 
	
	if(posNode == NULL)//删除结点不存在 
	{
		printf("无法删除,链表为空\n");
	}
	else
	{
		while(posNode->data != posData) //直到找到要删的数据 
		{
			posNodeFront = posNode;       // 向后移一个 
			posNode = posNodeFront->next; // 向后移一个 
			if(posNode == NULL){          // 为空不存在 
 				printf("无法删除,链表为空\n");
				return ;
			}
		}
		posNodeFront->next = posNode->next;//前一个结点指针直接指向删除结点后的结点 
		free(posNode);//释放删除结点 
	}
}

int main(){
	struct Node* list = createlist();
	insertNodeByHead(list,1);
	insertNodeByHead(list,2);
	insertNodeByHead(list,3); 
	printlist(list);
	deleteNodeByAppoin(list,2);
	printlist(list);
	system("pause");
	return 0;
} 















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eternity_GQM

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值