C语言实现单链表对结点的删除以及插入,均在头和尾操作

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

struct Node
{
	int data;
	struct Node *next;
};

void printList(struct Node *pHead)//打印链表
{
	struct Node *p = pHead->next;
	while(p)
	{
		printf("%d\n",p->data);
		p = p->next;
	}
}

int isEmpty(struct Node *pHead)//判断是否空链表
{
	return pHead->next == NULL;
}

size_t length(struct Node *pHead)//统计有效结点
{
	struct Node *p = pHead->next;
	size_t counter = 0;
	while(p)
	{
		p = p->next;
		++counter;
	}
	return counter;
}

void push_frnot(struct Node *pHead,int n)//头部插入法
{
	struct Node *pNew = malloc(sizeof(struct Node));
	pNew->data = n;
	pNew->next = pHead->next;
	pHead->next = pNew;
}

void push_back(struct Node *pHead,int n)//尾部插入插法
{
	if(isEmpty(pHead))
	{
		push_frnot(pHead,n);
	}
	else
	{
		struct Node *pNew = malloc(sizeof(struct Node));
		pNew->data = n;
		struct Node *p = pHead->next;
		while(p->next)
		{
			p = p->next;
		}
		p->next = pNew;
		pNew->next = NULL;
	}
}

void pop_front(struct Node *pHead)//头部删除法
{
	if(!isEmpty(pHead))
	{
		struct Node *p = pHead->next;
		pHead->next = p->next;
		free(p);
	}
}

void pop_back(struct Node *pHead)//尾部删除法
{
	if(length(pHead) >= 2)
	{
		struct Node *p = pHead->next;
		while(p->next->next)
		{
			p = p->next;
		}
		free(p->next);
		p->next = NULL;
	}
	else if(length(pHead) < 2)
	{
		pop_front(pHead);
	}
}

void destroyList(struct Node *pHead)//清除所有结点
{
	while(!isEmpty(pHead))
	{
		pop_front(pHead);
	}
}

int main(void)
{
	struct Node head;
	head.next = NULL;
	struct Node *pHead;
	pHead = &head;//定义一个空链表

	//测试
	push_frnot(pHead,1);
	push_frnot(pHead,2);
	push_frnot(pHead,3);
	push_back(pHead,5);
	pop_front(pHead);
	pop_back(pHead);
	printList(pHead);

	destroyList(pHead);
	printf("length = %u\n",length(pHead));//检查是否删除
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值