#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int DataType;
typedef struct LinkList
{
DataType data;
struct LinkList* next;
}LL;
void init(LL** ppl);//初始化
void clear(LL** ppl);//清空
void destroy(LL* pl);//销毁
void print(LL* pl);//打印
LL* node(DataType x, LL* next);//获取新节点
void addLast(LL* pl, DataType x);//添加
void add(LL* pl, int idx, DataType x);//索引添加
LL* removeLast(LL* pl);//删除
LL* remove(LL* pl, int idx);//索引删除
LL* getLast(LL* pl);//查询
LL* get(LL* pl, int idx);//索引查询
int find(LL* pl, DataType x);//查询索引
void set(LL* pl, int idx, DataType x);//修改
int isEmpty(LL* pl);//判空
int size(LL* pl);//获取大小
#include "LinkList.h"
void init(LL** ppl)
{
assert(ppl);
LL* new = (LL*)malloc(sizeof(LL));
if (new == NULL)
{
printf("失败");
exit(-1);
}
new->next = NULL;
*ppl = new;//头节点
}
void clear(LL** ppl)
{
assert(ppl);
init(ppl);
}
void destroy(LL* pl)
{
assert(pl);
LL* cur = pl;
LL* next = pl->next;
while (cur != NULL) {
next = cur->next;//获取下一个节点
free(cur);
cur = next;
}
}
void print(LL* pl)
{
assert(pl);
LL* cur = pl->next;
while (cur != NULL)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
LL* node(DataType x,LL* next)
{
LL* new = (LL*)malloc(sizeof(LL));
new->data = x;
new->next = next;
return new;
}
void addLast(LL* pl, DataType x)
{
assert(pl);
LL* new = node(x, NULL);
if (isEmpty(pl))
pl->next = new;
else
getLast(pl)->next = new;//找到最后一个节点
}
void add(LL* pl, int idx,DataType x)
{
assert(pl);
assert(idx >= 0);
LL* cur = idx==0?pl:get(pl,idx-1);//找到idx-1位置的节点
//idx-1节点不存在
if (cur==NULL)
return;
LL* new = node(x, cur->next);
cur->next = new;
}
LL* removeLast(LL* pl)
{
assert(pl);
if (isEmpty(pl))
return NULL;
LL* cur = size(pl)==1?pl:get(pl,size(pl)-2);//找到倒数第二个节点
LL* ans = cur->next;
cur->next = NULL;
return ans;
}
LL* remove(LL* pl, int idx)
{
assert(pl);
assert(idx >= 0);
if (isEmpty(pl))
return NULL;
LL* cur = idx==0 ? pl : get(pl, idx - 1);//找到idx-1位置的节点
//idx-1或idx节点不存在
if (cur==NULL||cur->next == NULL)
return NULL;
LL* ans = cur->next;
cur -> next = ans->next;
return ans;
}
LL* getLast(LL* pl)
{
assert(pl);
if (isEmpty(pl))//空表
return NULL;
LL* cur = pl;
while (cur->next!= NULL)
{
cur = cur->next;
}
return cur;
}
LL* get(LL* pl, int idx)
{
assert(pl);
assert(idx >= 0);
LL* cur = pl->next;
while (idx-- && cur != NULL)
{
cur = cur->next;
}
if (idx > 0)//节点不存在
return NULL;
return cur;
}
int find(LL* pl, DataType x)
{
assert(pl);
int idx = 0;
LL* cur = pl->next;
while (cur!=NULL)
{
if (cur->data == x)
return idx;
cur = cur->next;
idx++;
}
return -1;
}
void set(LL* pl, int idx, DataType x)
{
assert(pl);
assert(idx >= 0);
LL* cur = get(pl, idx);
if (cur == NULL)
return;
cur->data = x;
}
int isEmpty(LL* pl)
{
assert(pl);
return pl->next == NULL ? 1 : 0;
}
int size(LL* pl)
{
assert(pl);
if (pl->next == NULL)
return 0;
LL* cur = pl;
int size = 0;
while (cur->next != NULL)
{
cur = cur->next;
size++;
}
return size;
}