Link.h
typedef int ELEM_TYPE;
typedef struct Node
{
ELEM_TYPE data;
struct Node* next;
}Node,*Link;
void Init(Link phead); //初始化单链表
static Node* BuyNode(ELEM_TYPE val); //申请新的节点
bool InsertTail(Link phead,ELEM_TYPE val); //尾插法
bool InsertHead(Link phead,ELEM_TYPE val); //头插法
void Show(Link phead); //打印函数
bool DeleteKey(Link phead,ELEM_TYPE key); //删除key
void clear(Link phead); //清空
Link.cpp
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "Link.h"
/*初始化链表*/
void Init(Link phead)
{
assert(phead != NULL);
if(phead == NULL)
{
return ;
}
phead->next = NULL;
}
/*申请新的节点*/
static Link BuyNode(ELEM_TYPE val)
{
struct Node* pnewnode = (struct Node*)malloc(sizeof(Node));
assert(pnewnode != NULL);
pnewnode->data = val;
pnewnode->next = NULL;
return pnewnode;
}
bool InsertTail(Link phead,ELEM_TYPE val)
{
if(phead == NULL)
{
return false;
}
struct Node* pcur = phead;
while(pcur->next != NULL)//寻找最后一个节点
{
pcur = pcur->next;
}
struct Node* pnewnode = BuyNode(val);
pcur->next = pnewnode;
return true;
}
bool InsertHead(Link phead,ELEM_TYPE val)
{
if(phead == NULL)
{
return false;
}
struct Node* pnewnode = BuyNode(val);
pnewnode->next = phead->next;
phead->next = pnewnode;
return true;
}
bool DeleteKey(Link phead,ELEM_TYPE key)
{
if(phead == NULL)
{
return false;
}
struct Node* pfront = phead;
while(pfront->next != NULL)
{
if(pfront->next->data == key)
{
break;
}
pfront = pfront->next;
}
struct Node* pcur = pfront->next;
pfront->next = pcur->next;
free(pcur);
}
void Show(Link phead)
{
if(phead == NULL)
{
return ;
}
struct Node* pcur = phead->next;
while(pcur->next != NULL)
{
printf("%d ",pcur->data);
pcur = pcur->next;
}
printf("\n");
}
void clear(Link phead)
{
struct Node* pCur = phead;
struct Node* pNext ;
while(pCur->next != NULL)
{
pNext = pCur->next;
free(pCur);
pCur = pNext;
}
phead->next = NULL;
}
main.cpp
#include <stdio.h>
#include "Link.h"
int main()
{
Node head;
Init(&head);
for(int i=0; i<10; i++)
{
InsertHead(&head,i);
}
DeleteKey(&head,4);
Show(&head);
/*for(int i=0; i<10; i++)
{
InsertTail(&head,i);
}
Show(&head);*/
}
删除的过程