基础数据结构——链表代码实现C


//LinkedList -> 链表 头节点不包含数据
#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	int val;
	struct node* next;
}node;
typedef struct List
{
	int size;
	node* head;
}List;

void ListInit(List* lst);
void ListInsert(List* lst, int i, int elem);
void ListRemove(List* lst, int target);
void ListUpdate(List* lst, int i, int elem);
int ListIndex(List* lst, int target);
void ListDestroy(List* lst);
void ListPut(List* lst);

void ListInit(List* lst)
{
	lst->size = 0;
	lst->head = NULL;
}
void ListInsert(List* lst, int i, int elem)
{
	node* tmp;
	node* position;
	int j;
	if (i<0 || i>lst->size)
	{
		printf("index error");
		return;
	}
	if (i == 0)
	{
		tmp = (node*)malloc(sizeof(node));
		tmp->next = lst->head;
		tmp->val = elem;
		lst->head = tmp;
		lst->size++;
	}// 头插
	else
	{
		position = lst->head;
		for (j = 0; j < i-1; j++)
			position = position->next;
		// position指向插入位置的前一个元素
		tmp = (node*)malloc(sizeof(node));
		tmp->val = elem;
		lst->size++;
		tmp->next = position->next;
		position->next = tmp;
	}
}
void ListRemove(List* lst, int target)
{
	node* position;
	node* position2;
	if (lst->head == NULL)
		return;
	if (lst->head->val == target)
	{
		lst->size --;
		position = lst->head;
		lst->head = lst->head->next;
		free(position);
	}
	else
	{
		position = lst->head;
		while (position->next&&position->next->val != target)
			position = position->next;
		// positioin移动到待删除的前一个元素的位置
		if (position->next == NULL)
		{
			printf("target error");
			return;
		}
		position2 = position->next;
		position->next = position->next->next;
		free(position2);
		lst->size--;
	}
}
void ListUpdate(List* lst, int i, int elem)
{
	node* position;
	int j;
	if (i<0 || i>=lst->size)
	{
		printf("index error");
		return;
	}
	position = lst->head;
	for (j = 0; j < i; j++)
		position = position->next;
	// 指向待修改元素
	position->val = elem;
}
int ListIndex(List* lst, int target)
{
	node* position;
	int i = 0;
	position = lst->head;
	while (position && position->val != target)
	{
		position = position->next;
		i++;
	}
	if (position == NULL)
		return -1;
	return i;
}
void ListPut(List* lst)
{
	node* position = lst->head;
	while (position)
	{
		printf("%d-->", position->val);
		position = position->next;
	}
	printf("NULL");
}
void ListDestroy(List* lst)
{
	node* position;
	node* position2;
	position = lst->head;
	while (position)
	{
		position2 = position->next;
		free(position);
		position = position2;
	}
	lst->size = 0;
	lst->head = NULL;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值