(C语言)线性表的链式存储的实现

//带头结点单链表的实现
#include<stdio.h>
#include<malloc.h>

typedef struct LinkListNode
{
	int data;
	struct LinkListNode *next;
}Node,*pNode;

pNode Create(void);					//初始化,创建头结点
int Isempty(pNode);					//判断链表是否为空
void Traverse(pNode);				//遍历
int ListLen(pNode);					//求链表长
int Insert(pNode,int pos,int e);		//元素插入
int Delete(pNode,int pos,int *e);		//元素删除

int main()
{
	int val;							//用于返回删除元素
	pNode pHead=NULL;
	pHead=Create();

	if(Isempty(pHead))					//判断链表是否为空
		printf("链表为空!\n");
	else printf("链表不空!\n");	
	
	Insert(pHead,1,3);
	Insert(pHead,1,2);
	Insert(pHead,1,1);
	Traverse(pHead);

	if(Delete(pHead,3,&val)) printf("删除的元素为:%d\n",val);
	else printf("删除失败!\n");

	Traverse(pHead);					//遍历
	printf("链表长为:%d\n",ListLen(pHead));

	return 0;
}

//创建头结点,返回结点地址
pNode Create()
{
	pNode pHead=(pNode)malloc(sizeof(Node));
	pHead->next=NULL;
	return pHead;
}

//判断链表是否为空
int Isempty(pNode pHead)
{
	if(pHead->next==NULL)
		return 1;
	else return 0;
}

//遍历
void Traverse(pNode pHead)
{
	pNode p;
	if(Isempty(pHead))
		printf("链表为空!\n");
	else
	{
		printf("遍历结果为:");
		for(p=pHead->next;p!=NULL;p=p->next)
			printf("%d ",p->data);
		printf("\n");
	}
}

//求链表长
int ListLen(pNode pHead)
{
	int i=0;
	pNode p;
	p=pHead;
	while(p->next!=NULL)
	{
		i++;
		p=p->next;
	}
	return i;
}

//在第pos个位置插入元素,i为1到表长加一
int Insert(pNode pHead,int pos,int e)
{
	int i=0;
	pNode p=pHead;
	pNode pNew;

	while(p!=NULL&&i<pos-1)			//判断插入位置是否合理
	{
		p=p->next;
		i++;
	}
	if(i>pos-1||p==NULL)
		return 0;
	else
	{
		pNew=(pNode)malloc(sizeof(Node));
		pNew->data=e;
		pNew->next=p->next;
		p->next=pNew;
		return 1;
	}

}

//元素删除
int Delete(pNode pHead,int pos,int *pval)
{
	pNode p;
	pNode q;
	int i=0;
	p=pHead;

	while(p->next!=NULL&&i<pos-1)
	{
		p=p->next;
		i++;
	}
	if(i>pos||p->next==NULL)
		return 0;
	else
	{
		q=p->next;
		p->next=p->next->next;
		*pval=q->data;
		free(q);
		q=NULL;
		return 1;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值