C数据结构_链表

1.定义链表

//无头单向非循环链表

typedef struct SListNode
{
	int data;
	struct SListNode*next;
}SListNode;

typedef struct SList
{
	SListNode*head;
}SList;

2.链表基础功能的实现

//初始化
void Init(SList*p);

//销毁
void Destory(SList*p);

//创建新结点
SListNode *Buy(int x);

//头插
void PushFront(SList*p, int x);

//尾插
void PushBack(SList*p, int x);

//头删
void PopFront(SList*p);

//尾删
void PopBack(SList*p);

//查找
SListNode*Find(SList*p, int x);

//在pos后面插入
void InsertAfter(SListNode*pos, int x);

//在pos后面删除
void EraseAfter(SListNode*pos);

//打印
void Print(SList*p);

//初始化
void Init(SList*p)
{
	assert(p);
	p->head = NULL;
}

//销毁
void Destory(SList*p)
{
	SListNode*p1;
	SListNode*cur;
	for (cur = p->head; cur != NULL; cur = p1)
	{
		p1 = cur->next;
		free(cur);
	}
	p->head = NULL;
}

//创建新结点
SListNode *Buy(int x)
{
	SListNode*node = (SListNode*)malloc(sizeof(SListNode));
	assert(node);
	node->data = x;
	node->next = NULL;
	return node;
}

//头插
void PushFront(SList*p, int x)
{
	assert(p);
	SListNode*node = Buy(x);
	node->next = p->head;
	p->head = node;
}

//头删
void PopFront(SList*p)
{
	assert(p);
	assert(p->head);
	SListNode*old_head = p->head;
	p->head = p->head->next;
	free(old_head);
}

//尾插
void PushBack(SList*p, int x)
{
	assert(p);
	if (p->head == NULL)
	{
		PushFront(p, x);
		return;
	}
	SListNode*last = p->head;
	while (last->next != NULL)
	{
		last = last->next;
	}
	SListNode*node = Buy(x);
	last->next = node;
}

//尾删
void PopBack(SList*p)
{
	assert(p);
	assert(p->head);
	if (p->head->next == NULL)
	{
		PopFront(p);
		return;
	}
	SListNode*cur = p->head;
	while (cur->next->next != NULL)
	{
		cur = cur->next;
	}
	free(cur->next);
	cur->next = NULL;
}

//查找
SListNode*Find(SList*p, int x)
{
	SListNode*cur = p->head;
	for (; cur != NULL; cur = cur->next)
	{
		if (cur->data = x)
		{
			return cur;
		}
	}
	return NULL;
}

//在pos后面插入
void InsertAfter(SListNode*pos, int x)
{
	SListNode*node = Buy(x);
	node->next = pos->next;
	pos->next = node;	
}

//在pos后面删除
void EraseAfter(SListNode*pos)
{
	SListNode*next = pos->next->next;
	free(pos->next);
	pos->next = next;
}

//打印
void Print(SList*p)
{
	SListNode*cur = p->head;
	for (; cur != NULL; cur = cur->next)
	{
		printf("%d-->", cur->data);
	}
	printf("NULL\n");
}

 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值