链表是一种链式存储的线性表, 用一组地址任意的存储单元 存放线性表的数据元素, 称为存储单元的一个结点
头指针:指向第一个结点的指针
单链表的定义
typedef struct Node{
int value;//数据域
struct Node *next;指针域
}Node;//结构体变量
初始化
void slistinit(Node **ppfirst){
*ppfirst = NULL; //*ppfirst ->结构体指针
}
创建一个新节点
Node* buynode(int d){
Node* node = (Node*)malloc(sizeof(Node));
assert(node);
node->value = d;
node->next = NULL;
return node;
}
打印单链表
void slistprint(Node** ppfirst){
Node* cur = *ppfirst;
while (cur){
printf("%d->", cur->value);
cur = cur->next;
}
printf("NULL/n");
}
销毁单链表
void slistDestory(Node **ppfirst){
assert(*ppfirst);
while (*ppfirst!=NULL){
Node* cur = *ppfirst;
*ppfirst = (*ppfirst)->next;
free(cur);
}
}
删除指定结点
void slisterase(Node **ppfirst, Node *pos){
assert(*ppfirst&&pos);
Node *cur = *ppfirst;
while (cur)
{
if (cur == pos){
if (*ppfirst == pos){
*ppfirst = (*ppfirst)->next;
}
else{
cur->next = pos->next;
}
free(pos);
}
cur = cur->next;
}
}
头插
void slistpushfront(Node **ppfirst, int v){
assert(*ppfirst);
Node* cur=buynode(v);
cur->next=*ppfirst;
*ppfirst = cur;
}
头删
void slistpopfront(Node **ppfirst){
assert(*ppfirst);
Node *node;
node = *ppfirst;
*ppfirst = (*ppfirst)->next;
free(node);
}
尾插
void slistpushback(Node **ppfirst, int v){
Node* cur=buynode(v);
if (*ppfirst == NULL)
{
*ppfirst = cur;
return;
}
Node* pre = *ppfirst;
while (pre->next)
{
pre = pre->next;
}
pre->next = cur;
}
尾删
void slistpopback(Node **ppfirst){
assert(*ppfirst);
//存在一个结点时
if ((*ppfirst)->next == NULL){
*ppfirst = NULL;
return;
}
//多个节点
Node *cur = *ppfirst;
while (cur->next->next){
cur = cur->next;
}
free(cur->next);
cur->next = NULL;
}
查找指定元素的结点
Node* slistfind(Node** ppfirst, int v){
assert(*ppfirst);
Node* cur;
while (cur){
if (cur->value == v){
return cur;
}
cur = cur->next;
}
return NULL;
}
在指定位置前插入一个值
void insert(Node** ppfirst, int v,int pos){
assert(*ppfirst&&pos);
Node* pur = buynode(v);
Node* cur = *ppfirst;
while (cur->next!=NULL){
if (cur->next = pos)
{
cur->next = pur;
pur ->next = pos;
}
cur = cur->next;
}
}
删除第一个值为v的元素
void slistremove(Node **ppfirst, int v){
assert(*ppfirst);
Node *pur = NULL;
Node *pre = *ppfirst;
while (pre)
{
//第一个节点值为v
if (pre->value == v)
{
if(*ppfirst = pre)
{
*ppfirst=(*ppfirst)->next;
}else{
pur->next=pre->next;
}
free(pre);
return;
}
}
else{
pur = pre;
pre = pre->next;
}
}
}
删除所有值为v的元素
Node *slistremoveelements(Node **ppfirst, int v){
assert(*ppfirst);
Node *pre = NULL;
Node *pur = *ppfirst;
while (pur){
if (pur->value == v){
if (NULL == pre){
*ppfirst = pur->next;
free(pur);
pur = *ppfirst;//重点
}
else{
pre->next = pur->next;
free(pur);
pur = pre->next;
}
}
else{
pre = pur;
pur = pur->next;
}
}
return *ppfirst;
}