数据结构之链表实现

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

typedef struct node{
	int data;
	struct node * pNext;
} * pNode,Node;

pNode init();
bool append(pNode pHead,int data);
void show(pNode pHead);
int length(pNode pHead);
bool insert(pNode pHead,int data,int index);
bool del(pNode pHead,int index);

void main()
{
	pNode pHead = init();
	int len = length(pHead);
	printf("%d\n",len);
	append(pHead,3);
	append(pHead,4);
	append(pHead,10);
	insert(pHead,555,1);
	show(pHead);
	del(pHead,1);
	int len2 = length(pHead);
	printf("%d\n",len2);;
	show(pHead);

}


pNode init()// 初始化一个有头结点的空链表。
{
	pNode pHead = (pNode)malloc(sizeof(Node));
	if(NULL == pHead){
		exit(-1);
	}
	else{
		printf("初始化成功!\n");
		pHead->pNext = NULL;
	}
	return pHead;
}


bool append(pNode pHead,int data)//在链表尾部追加一个元素。
{
	pNode p = pHead;
	while(p->pNext != NULL)
	{
		p = p->pNext;
	}
	pNode pNew = (pNode)malloc(sizeof(Node));
		if(pNew != NULL)
		{
			pNew->data = data;
			pNew->pNext = NULL;
			p->pNext = pNew;
			return true;
		}
		else
			return false;
}

void show(pNode pHead)//打印链表
{
	pNode p = pHead;
	p = p->pNext;
	while(p != NULL)
	{
		printf("%d ",p->data);
		p = p->pNext;
	}
	printf("\n");
}

int length(pNode pHead)//返回链表长度
{
	pNode p = pHead;
	int len = 0;
	p = p->pNext;
	while(NULL != p)
	{
		p = p->pNext;
		len++;
	}
	return len;
}

bool insert(pNode pHead,int data,int index)//在链表Index位置插入一个元素data,当插入的元素位置大于长度时,返回失败。
{
	pNode pNew = (pNode)malloc(sizeof(Node));
	pNode p = pHead;
	int count = 0;
	int len = length(pHead);
	if(index > len || index < 1)
	{
		printf("插入序列号不正确\n");
		return false;
	}
	else
	{
		while(NULL!=pNew && count!=index-1)
		{
			p = p->pNext;
			count++;
		}
		pNew->data = data;
		pNew->pNext = p->pNext;
		p->pNext = pNew;	
		return true;
	}
}
bool del(pNode pHead,int index)//删除index位置的元素,当index大于链表的长度时,删除失败。
{
	pNode p = pHead;
	int count = 0;
	int len = length(pHead);
	if(index > len||index< 1 )
	{
		printf("不存在该节点\n");
		return false;
	}
	else{
		while(count != index-1)
		{
			p = p->pNext;
			count++;
		}
		pNode q = p->pNext;
		p->pNext = p->pNext->pNext;
		free(q);
	return true;
	}
}
</pre><pre name="code" class="cpp">少了反转和返回删除的元素。。。下次在实现吧。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值