数据结构 单链表实现 纯代码

单链表操作函数原型声明

node_t *list_init();
//显示单链表
void display(node_t *head);
//在单链表上查找第i个节点的存放地址
node_t *find(node_t *head,int i);
//在单链表上第I个节点后面插入值为x的节点
node_t *insert01(node_t *head,datatype x,int i);
node_t *insert02(node_t *head,datatype x,int i);
//在单链表上删除值为x的节点
node_t *delet(node_t *head,datatype x);

单链表节点数据结构体

//单链表
typedef int datatype;

typedef struct node
{
	struct node *next;
	//node_t *prev;
	datatype data;
}node_t;

完整代码

#include "stdio.h"
#include <malloc.h>
//单链表
typedef int datatype;

typedef struct node
{
	struct node *next;
	//node_t *prev;
	datatype data;
}node_t;


node_t *list_init();
//显示单链表
void display(node_t *head);
//在单链表上查找第i个节点的存放地址
node_t *find(node_t *head,int i);
//在单链表上第I个节点后面插入值为x的节点
node_t *insert01(node_t *head,datatype x,int i);
node_t *insert02(node_t *head,datatype x,int i);
//在单链表上删除值为x的节点
node_t *delet(node_t *head,datatype x);



node_t *list_init(void)
{
	node_t *head = (node_t *)malloc(sizeof(node_t));
	head->next = NULL;
	head->data = 0;
	return head;
}

void display(node_t *head)
{
	int count = 0;
	node_t *p = head;
	printf("----- List item -----\n");
	
	while(p != NULL)
	{
		
		printf("%d : [%d]\n",count,p->data);
		++count;
		p = p->next;
	}
}
//在单链表上查找第i个节点的存放地址
node_t *find(node_t *head,int i)
{
	node_t *p = head;
	int index = 1;

	if(i < 1 )
		return NULL;
	while((p != NULL) && (index++ != i))
	{
		p = p->next;
	}
	if(p != NULL)
		return p;
	return NULL;
}

node_t *insert02(node_t *head,datatype x,int i)
{
	node_t *p = head;
	p = find(head,i);
	if(p != NULL)
	{
		node_t *pnew = (node_t *)malloc(sizeof(node_t));
		if(pnew != NULL)
		{
			pnew->data = x;
			pnew->next = p->next;
			p->next = pnew;
		}
		else
		{
			printf("malloc error!\n");
		}
	}
	else
	{
		printf("have no the node!\n");
	}
	return head;
}
//在单链表上删除值为x的节点
node_t *delet(node_t *head,datatype x)
{
	node_t *p = head;
	node_t *pre = head;
	while((p != NULL) && (p->data != x))
	{
		pre = p;
		p = p->next;
	}
	if(p != NULL )
	{
		pre->next = p->next;
		free(p);
		p = NULL;
	}
	return head;
}
int main(void)
{
	node_t *list_head = list_init();
	
	//insert02(list_head,9,0);
	insert02(list_head,10,1);
	insert02(list_head,11,2);
	insert02(list_head,12,3);
	insert02(list_head,13,4);
	insert02(list_head,14,5);
	insert02(list_head,15,6);
	display(list_head);

	delet(list_head,14);
	delet(list_head,11);
	printf("after delet 14 11\n");
	display(list_head);
	insert02(list_head,55,2);
	insert02(list_head,66,5);
	printf("after insert 55 66\n");
	display(list_head);
	return 0;
}

运行结果

猜你喜欢

转载自blog.csdn.net/qq_29796781/article/details/81674415