aa

本文深入讲解了链表的基本操作,包括初始化、判断空链表、获取链表大小、遍历链表、插入节点、删除节点等。通过具体的C语言代码实现,帮助读者理解链表的动态内存管理和节点操作。

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

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

typedef struct Node
{
	int data;	//数据域
	struct Node * pNext; //指针域
}NODE, *PNODE; //NODE等价于struct Node    PNODE等价于struct Node *

PNODE init(PNODE pHead);
bool is_empty(PNODE pHead);
int size(PNODE pHead);
PNODE add(PNODE pHead, PNODE pTail,  int val);
PNODE add(PNODE pHead, int val);
void traveres(PNODE pHead); //遍历链表
bool insert_list(PNODE pHead, int pos, int val);
bool del(PNODE pHead, int pos);

int main(void)
{
	PNODE pHead = NULL;
	pHead = init(pHead);
	PNODE pTail = pHead;
	pTail->pNext = NULL;

	pTail = add(pHead, pTail, 1); //注意,改变pTail地址的方式,通过返回值的形式或者通过改变地址值
	pTail = add(pHead, pTail, 2);
	pTail = add(pHead, pTail, 3);
	
	insert_list(pHead, 2, 11);

	del(pHead, 1);

	traveres(pHead);

	printf("size=%d ", size(pHead));
	return 0;
}


PNODE add(PNODE pHead, PNODE pTail,  int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if (NULL == pNew)
	{
		printf("分配失败, 程序终止!\n");
		exit(-1);
	}
	pNew->data = val;
	pNew->pNext = NULL;
	pTail->pNext = pNew;
	pTail = pNew;
	return pTail;
}


PNODE init(PNODE pHead){
	pHead =  (PNODE)malloc(sizeof(NODE));	
	return pHead;
}

bool is_empty(PNODE pHead){
	if(NULL == pHead->pNext){
		return true;
	}else{
		return false;
	}
}

int size(PNODE pHead){
	PNODE p = pHead->pNext;
	int i = 0;
	while (NULL != p)
	{
		i++;
		p = p->pNext;
		
	}
	return i;
}

void traveres(PNODE pHead)
{
	PNODE p = pHead->pNext;

	while (NULL != p)
	{
		printf("%d  ", p->data);
		p = p->pNext;
	}
	printf("\n");
	
	return;
}

//pos从1开始,也就是当pos=2,在第二个位置之前插入元素
bool insert_list(PNODE pHead, int pos, int val)
{
	int i=0;
	PNODE p = pHead;
	while(NULL!=p && i<pos-1){
		p = p->pNext;
		i++;
	}
	
	if(NULL==p || i > pos-1){ //NULL==p校验pos的长度大于链表的长度,i > pos-1校验pos为0或负数的情况
		return false;
	}

	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if (NULL == pNew)
	{
		printf("动态分配内存失败!\n");
		exit(-1);
	}

	pNew->data = val;
	PNODE temp = p->pNext;
	p->pNext = pNew;
	pNew->pNext = temp;
	return true;
}

bool del(PNODE pHead, int pos)
{
	int i=0;
	PNODE p = pHead;
	while(NULL != p && i<pos-1){
		p = p->pNext;
	}

	if(NULL == p || i>pos-1){
		return false;
	}	

	PNODE temp = p->pNext;
	p->pNext = p->pNext->pNext;
	free(temp);
	temp = NULL;
	return true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值