1、类型重定义
typedef int DataType;
2、结构体定义
typedef struct Node
{
DataType _data;
struct Node* _next;
}Node,*pNode, *pList;
3、初始化链表
void InitLinkList(pList *pplist)
{
assert(pplist);
*pplist = NULL;
}
4、销毁链表
void Destroy(pList *pplist)
{
pNode cur = *pplist;
assert(pplist);
while (cur)
{
pNode del = cur;
cur = cur->next;
free(del);
}
*pplist = NULL;
}
5、尾部插入
void PushBack(pList *pplist, DataType x)
{
pNode cur = *pplist;
pNode pnode = NULL;
assert(pplist);
pnode = malloc(sizeof(Node));
if (pnode == NULL)
{
perror("PushBack::malloc");
exit(EXIT_FAILURE);
}
pnode->data = x;
pnode->next = NULL;
if (cur == NULL)
{
*pplist = pnode;
}
else
{
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = pnode;
}
}
6、尾部删除
void PopBack(pList *pplist)
{
pNode cur = NULL;
assert(pplist);
cur = *pplist;
if ((*pplist) == NULL)
{
return;
}
if ((*pplist)->next == NULL)
{
free(*pplist);
*pplist = NULL;
}
else
{
while (cur->next->next != NULL)
{
cur = cur->next;
}
free(cur->next);
cur->next = NULL;
}
}
7、头部插入
void PushFront(pList *pplist, DataType x)
{
pNode newnode = NULL;
assert(pplist);
newnode = BuyNode(x);
if (*pplist = NULL)
{
*pplist = newnode;
}
else
{
newnode->next = *pplist;
*pplist = newnode;
}
}
8、头部删除
void PopFront(pList *pplist)
{
pNode del = NULL;
assert(pplist);
del = *pplist;
if (*pplist)
{
return;
}
else
{
*pplist = del -> next;
free(del);
}
}
9、查找
pNode Find(pList plist, DataType x)
{
pNode cur = plist;
while (cur)
{
if (cur->data = x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
10、指定位置插入
void Insert(pList *pplist, pNode pos, DataType x)
{
pNode newnode = NULL;
assert(pplist != NULL);
assert(pos);
newnode = BuyNode(x);
if (*pplist == NULL)
{
PushFront(pplist, x);
}
else
{
newnode->next = pos->next;
pos->next = newnode;
}
}
11、指定位置删除
void Erase(pList *pplist, pNode pos)
{
pNode cur = NULL;
assert(pplist);
assert(pos);
if (*pplist == NULL)
{
return;
}
cur = *pplist;
while (cur && (cur->next != pos))
{
cur = cur->next;
}
if (cur != NULL)
{
cur->next = pos->next;
free(pos);
}
}
12、删除指定元素
void Dellet(pList *pplist, DataType x)
{
pList cur = NULL;
pList prev = NULL;
assert(pplist);
cur = *pplist;
if (*pplist == NULL)
{
return;
}
else
{
while (cur)
{
if (cur->data == x)
{
pNode del = cur;
//第一个结点
if (cur == *pplist)
{
*pplist = cur->next ;//制空
free(del);
}
else
{
prev->next = cur->next;
free(del);
}
return;
}
else
{
prev = cur;
cur = cur->next;
}
}
}
}
13、删除指定的所有元素
void Delletall(pList *pplist, DataType x)
{
pList cur = NULL;
pList prev = NULL;
assert(pplist);
cur = *pplist;
if (*pplist == NULL)
{
return;
}
else
{
while (cur)
{
if (cur->data == x)
{
pNode del = cur;
//第一个结点
if (cur == *pplist)
{
*pplist = cur->next;//制空
free(del);
cur = *pplist;
}
else
{
prev->next = cur->next;
free(del);
cur = prev -> next;
}
}
else
{
prev = cur;
cur = cur->next;
}
}
}
}
//打印单向链表
void Display(pList plist)
{
pNode cur = plist;
while (cur)
{
printf("%d-->", cur->data);
cur = cur->next;
}
printf("over\n");
}