不带头结点的单链表

不带头结点的单链表是以一个指针来存储第一个结点的位置,相当于带头结点单链表的头结点只存储地址而不存储目前的结点个数。插入删除和带头结点的链表不一样外,其它功能基本相似。

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


typedef struct Node
{
	int data;
	struct Node *next;
}Node, *List;

//单链表的初始化
void InitList(List *head)
{
	assert(head != nullptr);
	*head = nullptr;
}

//创建一个节点
Node* createNode(List head,int val)
{
	Node *node = (Node *)malloc(sizeof(Node));
	assert(node != nullptr);
	node->data = val;
	node->next = nullptr;
	return node;
}

//头插
bool Insert_head(List *head, int val)
{
	//Node *p = (Node *)malloc(sizeof(Node));
	//p->data = val;
	assert(head != nullptr);
	Node *p = createNode(*head, val);
	p->next = *head;
	*head = p;
	return true;
}

//尾插法
bool tailInsert(List *head, int val)
{
	assert(head != nullptr);
	Node *p = createNode(*head, val);
	if (*head == nullptr)
	{
		*head = p;
		return true;
	}
	
	Node *q;
	for (q = *head; q->next != NULL; q = q->next);
	{
		//p->next = q->next;
		q->next = p;
		return true;
	}
}

//找前驱
Node* FindPrior(List head, int pos)       //找目标结点的前一个
{
	List p = head;
	while (pos - 1)
	{
		p = p->next;
		pos--;
	}
	return p;
}

//长度
int length(List head)
{
	//assert(head != nullptr);
	List cur = head;
	int count = 0;
	while (cur != nullptr)
	{
		count++;
		cur = cur->next;
	}
	return count;
}

//任意位置插入
bool Insert(List *head, int val,int pos)
{
	assert(head != nullptr);
	if (pos<0 || pos>length(*head))
		return false;

	if (pos == 0)
	{
		if (Insert_head(head, val)) 
			return true;
	}
	List p = FindPrior(*head, pos);
	List q = createNode(*head,val);
	q->next = p->next;
	p->next = q;
	return true;
}

//删除任意节点
bool Delete(List *head, int pos)
{
	assert(head != nullptr);
	if (pos<0 || pos>length(*head))
		return false;

	List p = FindPrior(*head, pos);
	List q = p->next;
	p->next = q->next;
	free(q);
	q = nullptr;
	return true;
}

//逆置
void reserve(List *head)
{
	assert(*head != nullptr);
	List cur = *head;
	List pnext = cur;
	*head = nullptr;

	while (cur != nullptr)
	{
		pnext = cur->next;
		cur->next = *head;
		*head = cur;
		cur = pnext;
	}
}

//打印
void Show(List *head)
{
	assert(head != nullptr);
	List p = *head;
	while (p != nullptr)
	{
		printf("%d  ", p->data);
		p = p->next;
	}
	printf("\n");
}

//删除
void destory(List *head)      
{
	Node *cur = *head;
	Node *pnext = cur;

	while (cur != nullptr)
	{
		pnext = cur->next;
		free(cur);
		cur = pnext;
	}
	*head = nullptr;
}



int main()
{
	List head;
	InitList(&head);
	for (int i = 0; i < 10; i++)
	{
		tailInsert(&head, i);
	}
	Show(&head);
	Insert(&head,33,5);
	Show(&head);

	Delete(&head, 3);
        reserve(&head);
	Show(&head);
	int len = length(head);
	printf("%d\n",len);
	destory(&head);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值