栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c语言实现数据结构单链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c语言实现数据结构单链表

//单链表不能找前驱结点,都是通过遍历来的
//不带头指针的单链表
#include 
#include 

typedef struct LNode
{
	int data;
	struct LNode* next; 
}Lnode, * linkList;
//判断链表是否为空
bool Empty(linkList L)//不修改指针的内容
{
	return (L == NULL);
}

//不带头结点的链表
bool InitList1(linkList &L) 
{
	L = NULL;  //空表 没有指针
	return true;
}
//带头结点的链表
bool InitiList2(linkList &L)
{
	L = (Lnode*)malloc(sizeof(Lnode)) ;
	if(Empty(L))	//分配结点失败
		return false;
	L->next = NULL;
	return true;
}
//不带头结点的插入,当插入第一位时,要额外进行处理
bool ListInsert1(linkList &L, int i, int e)
{
	if(i<1)
		return false;
	if(i == 1)
	{
		LNode* s = (LNode*)malloc(sizeof(LNode));
		s->data = e;
		s->next = L;
		L = s;
		return true;
	}

	LNode* p;//扫描所有的节点
	p=L;//将指针指向头结点
	int j=1;//当前扫描到第几个结点,从第一个节点进行扫描
	while(p!=NULL && jnext;
		j++;
	}
	if(p==NULL) //比如有五个元素 结果要插到第七个位置就出错了
		return false;
	LNode* s = (LNode*)malloc(sizeof(LNode));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}
//带头结点的按位序尾插入元素,比如插到第三个 就是插到第二个后面
bool ListInsert2(linkList &L, int i, int e)
{
	if(i<1)
		return false;
	LNode* p;//扫描所有的节点
	p=L;//将指针指向头结点
	int j=0;//当前扫描到第几个结点
	while(p!=NULL && jnext;
		j++;
	}
	if(p==NULL) //比如有五个元素 结果要插到第七个位置就出错了
		return false;
	LNode* s = (LNode*)malloc(sizeof(LNode));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return true;
}
//前插的原理是用尾插法在p节点后面尾插,再将p节点与插入节点数据互换,需要找到第i个结点,而尾插法需要找到第i-1个结点
bool PriorNode(LNode* p, LNode* s,int e)
{
	if(p == NULL || s==NULL)
		return false;
	s->next = p->next;
	p->next = s;
	s->data = p->data;
	p->data = e;
	return true;
}
//删除指定结点,带头结点
bool ListDelet(linkList &L,int i, int &e)
{
	if(i<1)
		return false;
	int j=0;
	linkList p;
	linkList s;
	p = L;
	while(p!=NULL && jnext;
		e = s->data;
		p->next=s->next;
		free(s);
		return true;
	}
	if(p->next==NULL || p==NULL)
		return false;

}
int Length(linkList L)
{
	LNode* p = L;
	int length = 0;
	while(p->next!=NULL)
	{
		p=p->next;
		length++;
	}
	return length;
}
void ShowList(linkList L)
{
	LNode* p = L;
	for(int i=1;i<=Length(L);i++)
	{
		p=p->next;
		printf("第%d个结点的内容是%dn",i,p->data);
	}
}
//头插法建立一个单链表,相当于栈
linkList CreatList()
{
	linkList L;
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;//初始化尾结点必须为空
	Lnode* s;int x;
	printf("请输入结点的值");
	scanf("%d",&x);
	while(x!=999)
	{
		s = (LNode*)malloc(sizeof(LNode));//创建一个新的结点,并用指针指向
		s->data = x;
		s->next = L->next;
		L->next = s;
		printf("请输入结点的值");
		scanf("%d",&x);
	}

	return L;

}

void main(void)
{
	linkList L;//指向单链表的指针,在这里没有初始化一个结点

	InitiList2(L);
	ListInsert2(L, 1, 1);
	ListInsert2(L, 2, 2);
	ListInsert2(L, 3, 3);
	ListInsert2(L, 4, 4);
	ShowList(L);

	linkList L2 = CreatList();
	ShowList(L2);
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/317641.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号