C/C++语言实现数据结构之单链表(带头结点)

单链表相关知识

用C语言简单实现

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

typedef int ElemType;  //让链表存储数据为int,如果想泛化能力更强,可以采用C++的模板技术
typedef struct Node
{
	ElemType data;
	Node* next;
}*PNode;

//初始化链表
bool InitPNode(PNode& L)
{
	L = (Node*)malloc(sizeof(Node));
	if (L == NULL)
	{
		return false;
	}
	L->next = NULL;
	return true;
}

//利用数组初始化链表(头插法)
void CreateListH(PNode&L,ElemType A[],int A_size)
{
	int i = 0;
	for (i;i<A_size;++i)
	{
		PNode temp = (PNode)malloc(sizeof(Node));
		temp->data = A[i];
		temp->next = L->next;
		L->next = temp;
	}

}

//利用数组初始化链表(尾插法)
void CreateListT(PNode& L, ElemType A[], int A_size)
{
	PNode T = L;
	while (T->next != NULL)
	{
		T = T->next;
	}
	int i = 0;
	for (i; i < A_size; ++i)
	{
		PNode temp = (PNode)malloc(sizeof(Node));
		temp->data = A[i];
		T->next = temp;
		T = temp;
		T->next = NULL;
	}

}

//打印链表
void PrintList(PNode& L)
{
	if (L == NULL)
		return;
	PNode temp = L->next;
	while (temp != NULL)
	{
		printf("%d ",temp->data);
		temp = temp->next;
	}
	printf("\n");
}

//返回链表当前的长度
int reListLength(PNode& L)
{
	int i = 0;
	PNode temp = L->next;
	while (temp != NULL)
	{
		++i;
		temp = temp->next;
	}
	return i;
}

//第i号位置插入元素 e,若i位置不符合要求,返回false
bool InsertI(PNode& L, int i, ElemType e)
{
	if (i<1 || i>reListLength(L))
		return false;
	PNode T = L;
	int j = 1;
	while (j<i)  //跑到i-1位置
	{
		T = T->next;
		++j;
	}
	PNode temp = (PNode)malloc(sizeof(Node));
	temp->data = e;
	temp->next = T->next;
	T->next = temp;
	return true;
}

//删除第i号位置的元素
bool DeleteI(PNode&L,int i)
{
	if (i<1 || i>reListLength(L))
		return false;
	PNode T = L;
	int j = 1;
	while (j < i)
	{
		T = T->next;
		++j;
	}
	PNode q = T->next;
	T->next = q->next;
	free(q);
	return true;
}

//删除整个链表
bool DeleteL(PNode&L)
{
	if (L == NULL)
	{
		return false;  //链表本身为空,返回false表示未执行删除操作
	}
	while (L->next!=NULL)
	{
		PNode temp = L->next;
		L->next = temp->next;
		free(temp);
	}
	return true;
}

int main()
{
	PNode L; //L为头结点,不含数据
	if (InitPNode(L))
	{
		printf("链表初始化成功!\n");
	}
	printf("链表长度为:%d\n", reListLength(L));
	int A[5] = {1,2,3,4,5};
	//CreateListH(L,A,5);
	CreateListT(L, A, 5);
	PrintList(L);
	printf("链表长度为:%d\n", reListLength(L));
	InsertI(L,5,6);
	PrintList(L);
	printf("链表长度为:%d\n", reListLength(L));
	DeleteI(L,6);
	PrintList(L);
	printf("链表长度为:%d\n", reListLength(L));
	if (DeleteL(L))
	{
		printf("删除链表成功");
	}
	PrintList(L);
	printf("链表长度为:%d\n", reListLength(L));
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值