C语言 不带头结点的单链表的实现和相关操作。

C语言 不带头结点的单链表的实现和相关操作。

#include<stdio.h>
#include<stdlib.h>
typedef int DAT;
typedef struct node//定义一个结构体 
{
    DAT data;//存放数据 
    struct node *next;//指向下一个结构体的指针 
}Node;
void init_list(Node **pL)//初始化
{
    (*pL) = NULL;
}
Node* make_node(DAT data)//生成新节点
{
    Node *NewNode = (Node*)malloc(sizeof(Node));
    if (NewNode == NULL)
    {
        printf("动态开辟内存空间失败\n");
        return;
    }
    NewNode->data = data;
    NewNode->next = NULL;
    return NewNode;
}
void push_back_list(Node **pL, DAT data)//尾插法插入链表 
{
    Node *NewNode = make_node(data);
    if (*pL == NULL)
    {
        *pL = NewNode;
        return;
    }
    Node *cur = *pL;
    while (cur->next)
    {
        cur = cur->next;
    }
    cur->next = NewNode;
}
void push_front_list(Node **pL,DAT data)//头插法 插入链表 
{
	Node *newNode=make_node(data);
	if(*pL==NULL)
	{
		*pL=newNode;
		return;
	 } 
	newNode->next=*pL;
	*pL=newNode;
}
void pop_front_list(Node **pL)//头删链表 
{
	if(pL==NULL)
	{
		printf("链表为空,头删失败。");
		return; 
	}
	(*pL)=(*pL)->next;
 } 
void pop_back_list(Node **pL)//尾删链表
{
	if(pL==NULL)
	{
		printf("链表为空,尾删失败。");
		return; 
	}
	Node *cur=*pL;
	Node *pre=NULL;
	if((*pL)->next==NULL)
	{
		(*pL)=NULL;
		free(cur);
		cur=NULL;
		return;
	}
	while(cur->next )
	{
		pre=cur;
		cur=cur->next ;		
	}
	free(cur);
	cur=NULL;
	pre->next =NULL;
 } 
void print_list(Node *pL)//打印单链表
{
    Node *cur = pL;
    while (cur)
    {
        printf("%d-->", cur->data);
        cur = cur->next;
    }
    printf("NULL\n");
}
void destroy_list(Node **pL)//销毁链表 
{
	if(*pL==NULL)
	return;
	Node *pre=NULL;
	Node *cur=*pL;
	while(cur)
	{
		pre=cur;
		cur=cur->next;
		free(pre);
		pre=NULL;
	 } 
	*pL=NULL;
 } 
int main()
{
	Node *first = NULL;
    init_list(&first);//初始化链表 
    push_back_list(&first, 1);//尾插法 插入链表 
    print_list(first);//打印链表
    push_back_list(&first, 12);//尾插法 插入链表
    print_list(first);//打印链表
    push_back_list(&first, 123);//尾插法 插入链表
    print_list(first);//打印链表 
    push_front_list(&first,4);//头插法 插入链表
	print_list(first);//打印链表
    push_front_list(&first,45);//头插法 插入链表
	print_list(first);//打印链表	
    push_front_list(&first,456);//头插法 插入链表
	print_list(first);//打印链表
	pop_front_list(&first);//头删链表
	print_list(first);//打印链表
	pop_back_list(&first);//尾删链表
	print_list(first);//打印链表
	destroy_list(&first);//销毁链表
	print_list(first);//打印链表		
	return 0;
 } 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值