数据结构---线性表链式实现

主要参考的严老师那本教材上的:

写的比较快,可能代码的可读性不是很好。

//带头结点的单链表
#include <stdio.h>
#include <malloc.h>
#define ElemType int
typedef struct node
{
	ElemType data;
	struct node *next;
}node;

//用data来初始化并分配内存,返回一个新节点
node *newNode(ElemType data)
{
	node *pNode=(node *)malloc(sizeof(node));
	if(!pNode)
		return NULL;//失败
	pNode->data=data;
	pNode->next=NULL;
	return pNode;
}

//创建n个元素的链表(主要是分配空间),并且输入来初始化
node* createList(int n)
{
	node *head=(node *)malloc(sizeof(node));
	if(!head)
		return NULL;//失败
	head->next=NULL;
	node *cur=head;
	for (int i=0; i<n; i++)
	{
		ElemType tmp;
		scanf("%d",&tmp);
		node *tmpNode=newNode(tmp);
		if(!tmpNode)
			return NULL;//失败
		cur->next=tmpNode;
		cur=cur->next;
	}
	return head;
}

//输出链表所有元素
void printList(node *head)
{
	node *cur=head;
	while(cur->next!=NULL)
	{
		printf("%d ",cur->next->data);
		cur=cur->next;
	}
	printf("\n");
}

//按照位置查找pos(除去头结点外,第一个元素算作位置0,从0开始)处元素,取得数据域
int searchByPos(node *head,int pos,ElemType *e)
{
	node *cur=head;
	for (int i=0; i<pos && cur->next!=NULL; i++)
		cur=cur->next;
	if(cur->next!=NULL)
	{
		*e=cur->next->data;
		return 1;
	}
	else
		return 0;

}

//在位置pos(前)插入一个新元素,pos:除去头结点外,有效节点的pos从0开始
//pos合法范围:0--len-1;不过程序中有检测
int insertByPos(node *head,int pos,ElemType e)
{
	node *cur=head;
	node *tmpNode=newNode(e);
	int i;
	if(!tmpNode)
		return 0;//插入失败
	for (i=0; i<pos && cur->next!=NULL; i++)
		cur=cur->next;
	if(cur->next==NULL&&i>=pos)//可以直接在尾部追加的情况
	{
		cur->next=tmpNode;
		return 1;
	}
	else if(i>=pos)
	{
		tmpNode->next=cur->next;
		cur->next=tmpNode;
		return 1;
	}
	else
		return 0;//pos位置不存在造成的无法插入
	
}

//删除某个位置的元素,用*e保存它的值
int deleteByPos(node *head,int pos,ElemType *e)
{
	node *cur=head;
	int i;
	for (i=0; i<pos && cur->next!=NULL; i++)
		cur=cur->next;
	if(cur->next==NULL)
		return 0;//不存在这个位置,删除失败
	else
	{
		node *tmp=cur->next;
		cur->next=cur->next->next;
		free(tmp);
		return 1;
	}
}

int main()
{
	node *head=createList(5);
	printList(head);
	insertByPos(head,3,55);
	printList(head);
	ElemType tmp;
	deleteByPos(head,5,&tmp);
	printList(head);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值