带头结点单链表

Link.h

typedef int ELEM_TYPE;
typedef struct Node
{
	ELEM_TYPE data;
	struct Node* next;
}Node,*Link;

void Init(Link phead);  //初始化单链表
static Node* BuyNode(ELEM_TYPE val);  //申请新的节点
bool InsertTail(Link phead,ELEM_TYPE val);  //尾插法
bool InsertHead(Link phead,ELEM_TYPE val);  //头插法
void Show(Link phead);     //打印函数
bool DeleteKey(Link phead,ELEM_TYPE key);  //删除key
void clear(Link phead);   //清空

Link.cpp

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "Link.h"

/*初始化链表*/
void Init(Link phead)
{
	assert(phead != NULL);
	if(phead == NULL)
	{
		return ;
	}
	phead->next = NULL;
}


/*申请新的节点*/
static Link BuyNode(ELEM_TYPE val)
{
	struct Node* pnewnode = (struct Node*)malloc(sizeof(Node));
	assert(pnewnode != NULL);
	pnewnode->data = val;
	pnewnode->next = NULL;
	return pnewnode;
}



bool InsertTail(Link phead,ELEM_TYPE val)
{
	if(phead == NULL)
	{
		return false;
	}
	struct Node* pcur = phead;
	while(pcur->next != NULL)//寻找最后一个节点
	{
		pcur = pcur->next;
	}
	struct Node* pnewnode = BuyNode(val);
	pcur->next = pnewnode;
	return true;
}

bool InsertHead(Link phead,ELEM_TYPE val)
{
	if(phead == NULL)
	{
		return false;
	}
	struct Node* pnewnode = BuyNode(val);
	pnewnode->next = phead->next;
	phead->next = pnewnode;
	return true;
}


bool DeleteKey(Link phead,ELEM_TYPE key)
{
	if(phead == NULL)
	{
		return false;
	}
	struct Node* pfront = phead;
	while(pfront->next != NULL)
	{
		if(pfront->next->data == key)
		{
			break;
		}
		pfront = pfront->next;
	}

	struct Node* pcur = pfront->next;
	pfront->next = pcur->next;
	free(pcur);
}

void Show(Link phead)
{
	if(phead == NULL)
	{
		return ;
	}
	struct Node* pcur = phead->next;
	while(pcur->next != NULL)
	{
		printf("%d ",pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}


void clear(Link phead)
{
	struct Node* pCur = phead;
	struct Node* pNext ;
	while(pCur->next != NULL)
	{
		pNext = pCur->next;
		free(pCur);
		pCur = pNext;
	}
	phead->next = NULL;
}

main.cpp

#include <stdio.h>

#include "Link.h"

int main()
{
	Node head;
	Init(&head);
	for(int i=0; i<10; i++)
	{
		InsertHead(&head,i);
	}
	DeleteKey(&head,4);
	Show(&head);
	/*for(int i=0; i<10; i++)
	{
		InsertTail(&head,i);
	}
	Show(&head);*/
}

删除的过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值