//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;
}
基础数据结构——链表代码实现C
最新推荐文章于 2024-08-18 12:51:45 发布