单链表的基本操作

#include <stdio.h>
#include <malloc.h>
#define NULL
#define true 1
#define false 0

typedef int ElemType;
typedef struct LNode{
	ElemType date;
	struct LNode *next;
}ListNode;
0.头插法创建单链表 
//void CreateList(LinkNode *&L,ElemType a[],int n)
//{
//	L=(ListNode*)malloc(sizeof(ListNode));
//	L->next=NULL;
//	int i;
//	for(i=0;i<n;i++)
//	{
//		s=(ListNode*)malloc(sizeof(ListNode));
//		s->date=a[i];
//		s->next=L->next;
//		L->next=s;
//	}
//}
 



//1.尾插法创建单链表 
void CreateListR(LinkNode *&L,ElemType a[],int n)
{
	L=(LinkNode*)malloc(sizeof(LinkNode));
	L->next=NULL;
	LinkNode *s,*r;
	int i;
	for(i=0;i<n;i++){
		s=(LinkNode*)malloc(sizeof(LinkNode));
		s->date=a[i];
		r->next=s;
		r=s;
	}
	r->next=NULL;	
}
//2.销毁线性表
void DestoryList(LinkNode *&L)
{
	LinkNode *pre=L,*p=L->next;
	while(p!=NULL){
		free(pre);
		pre=p;
		p=pre->next;
	}
	free(pre);
 } 

//3.判断线性表是否为空表
bool ListEmpty(LinkNode *L)
{
	return(L->next==NULL);
 } 
//4.求线性表的长度
int ListLength(LinkNode *L) 
{
	ListNode *p=L;
	int n;
	while(p->next!=NULL)
	{
		n++;
		p=p->next;
	}
	return (n);
}

//5.输出单链表
void DispList(ListNode *L)
{
	LinkNode *p=L->next;
	while(p!=NULL)
	{
		printf("%d",p->date);
		p=p->next;
	}
	printf("\n");
 } 

//6.求单链表L中位置i的数据元素
bool GetElem(LinkNode *L,int i,ElemType &e)
{
	int j=0;
	LinkNode *p=L;
	while(j<i&&p!=NULL)
	{
		j++;
		p=p->next;
	}
	if(p==NULL)
		return false;
	else
	{
		e=p->date;
		return true;
	}
 } 

//7.根据数据元素查找位置
int LocateElem(ListNode *L,ElemType e)
{
	int i=1;
	LinkNode *p=L->next;
	while(p!=NULL&&p->date!=e)
	{
		p=p->next;
		i++;
	}
	if(p==NULL)
	return flase;
	else
	{
		e=p->date;
		return (i);
	}
 } 
 
//8.插入数据 
void ListInter(LinkNode *&L,int i,ElemType e)
{
	p=L;
	j=0;
	while(p!=NULL&&j<i-1)
	{
		p=p->next;
		j++;
	}
	if(p=NULL)
		return false;
	else
	{
		s=(LinkNode*)malloc(sizeof(LinkNode));
		s->date=e;
		s->next=p->next;
		p->next=s;
		return true;
	}
		
	
}
//删除数据元素
bool ListDelete(LinkNode *L,int i,ElemType &e)
{
	int j=0;
	LinkNode *p=L,*q;
	while(j<i-1&&p!=NULL)
	{
		j++;
		p=p->next;
	}
	if(p==NULL)
		return false;
	else
	{
		q=p->next;
		if(q==NULL)
		return false;
		
		e=q->date;
		p->next=q->next;
		free(q);
		return true;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值