C语言实现单链表的代码教程
2018-02-12 12:01:00      个评论    来源：baidu_37964044的博客

```#ifndef __LINKLIST_H__
#include
#include
#include
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* next;

}Node;
#endif```

```#include"LinkList.h"
{
}
{   //开辟空间
Node *node=(Node*)malloc(sizeof(Node));
//赋值
node->next = NULL;
node->data = x;
return node;
}
{   //1.空
{
printf("NULL\n");
return;
}
//2.非空
{
}
printf("NULL\n");
}
{
//1.空
{
}
//2.非空
else
{
//找尾
while (tail->next)
{
tail = tail->next;
}
//插入

}

}
{
//检查参数
//1.空
{
return;
}
//2.有一个结点
{
}
//3.两个及其两个以上结点
else
{
//找尾的前一个结点
Node *prev = NULL;//用于找最后一个结点的前一个结点  不能直接释放尾，否则指向尾结点的指针野指针，因此要找到指向尾的指针，置成空
while (tmp->next)
{
prev = tmp;
tmp = tmp->next;
}
prev->next = NULL;
free(tmp);//切记一定要释放，因为它是malloc出来的，也就是动态开辟出来的 。否则内存泄漏
tmp = NULL;

}

}
{
//1.链表为空
{
}
//2.链表非空
else
{
}
}
{
//1.空
{
return;
}
//2.一个结点
{
}
//3.两个及两个以上结点
else
{
}
}
{
while (cur)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;//没找到
}
{
//1.pos为头结点
{
}
//2.非头结点
else
{
while (prev->next !=pos)
{
prev = prev->next;
}
prev->next = tmp;
tmp->next = pos;
}
}
{
//1.pos为头节点
{
}
//2.pos为尾结点
else if (pos->next == NULL)
{
}
//3.非头尾结点
else
{
Node* next = pos->next;
if (prev->next != pos)
{
prev = prev->next;
}
prev->next = next;
free(pos);
pos = NULL;
}
}

```

test.c //测试

```#include"LinkList.h"
void test1()
{   //测试PopBack,PushBack
Node *list = NULL;
PrintList(list);
PushBack(&list, 4);
PushBack(&list, 3);
PushBack(&list, 2);
PushBack(&list, 1);
PopBack(&list);
PopBack(&list);
PrintList(list);
PopBack(&list);
PopBack(&list);
PrintList(list);

}
void test2()
{   //测试PopFront,PushFront
Node *list = NULL;
PushFront(&list, 1);
PushFront(&list, 2);
PushFront(&list, 3);
PushFront(&list, 4);
PrintList(list);
PopFront(&list);
PrintList(list);
PopFront(&list);
PopFront(&list);
PopFront(&list);
PrintList(list);

}
void test3()
{   //测试Find Insert  Erase
Node *list = NULL;
PushFront(&list, 1);
PushFront(&list, 2);
PushFront(&list, 3);
PushFront(&list, 4);
PrintList(list);
Node* pos = Find(list, 4);
Insert(&list, pos, 20);
PrintList(list);
Insert(&list, pos->next, 30);
PrintList(list);
Erase(&list, pos);
PrintList(list);

}
int main()
{
//test1();
//test2();
test3();
system("pause");
return 0;
}```