1、创建头指针
Link_t *create_link()
{
Link_t *plink = (Link_t*)malloc(sizeof(Link_t));
if(NULL == plink)
{
perror("malloc fail");
return NULL;
}
plink->phead = NULL;
plink->clen = 0;
return plink;
}
2、头插
int push_link_head(Link_t *plink,Datatype data)
{
Link_node_t *pnode = (Link_node_t*)malloc(sizeof(Link_node_t));
if(pnode == NULL)
{
perror("malloc fail");
return -1;
}
pnode->data = data;
pnode->pnext = NULL;
pnode->pnext = plink->phead;
plink->phead = pnode;
plink->clen++;
return 0;
}
3、尾插
int push_link_behind(Link_t *plink,Datatype data)
{
Link_node_t *pnode = (Link_node_t*)malloc(sizeof(Link_node_t));
if(pnode == NULL)
{
perror("fail malloc");
return -1;
}
pnode->data = data;
pnode->pnext = NULL;
Link_node_t *p = plink->phead;
if(p)
{
while(p->pnext)
{
p = p->pnext;
}
p->pnext = pnode;
}else
{
plink->phead = pnode;
}
plink->clen++;
return 0;
}
4、头删
int pop_link_head(Link_t *plink)
{
Link_node_t *p = plink->phead;
if(p)
{
plink->phead = p->pnext;
free(p);
}
plink->clen--;
return 0;
}
5、尾删
int pop_link_behind(Link_t *plink)
{
Link_node_t *p = plink->phead;
if(p)
{
if(p->pnext)
{
while(p->pnext->pnext)
{
p = p->pnext;
}
free(p->pnext);
p->pnext = NULL;
plink->clen--;
}
else{
pop_link_head(plink);
}
}
return 0;
}
6、查找
Link_node_t *find_link(Link_t *plink,Datatype data)
{
Link_node_t *p = plink->phead;
while(p)
{
if(p->data == data)
{
return p;
}
p = p->pnext;
}
return NULL;
}
7、查链表中心位置
Link_node_t *find_link_center(Link_t *plink)
{
Link_node_t *p = plink->phead;
int t = 0;
if(plink->clen == 1)
{
return plink->phead;
}
while(p)
{
t++;
if(t == plink->clen / 2)
{
printf("center = %d\n",p->data);
return p;
}
p = p->pnext;
}
return NULL;
}
8、快慢指针查找倒数第k个链表
Link_node_t * find_link_k_fast(Link_t *plink,int k)
{
Link_node_t *pfast = plink->phead;
Link_node_t *pslow = pfast;
if(pfast == NULL)
{
return NULL;
}
while(k > 1)
{
if(!pfast->pnext)
return NULL;
pfast = pfast->pnext;
k--;
}
while(pfast)
{
pfast = pfast->pnext;
if(!pfast)
return pslow;
pslow = pslow->pnext;
}
return pslow;
}
9、链表倒置
void link_inversion(Link_t *plink)
{
Link_node_t *p = plink->phead;
if(!p)
return;
plink->phead = NULL;
Link_node_t *ptmp = p->pnext;
plink->phead = p;
p->pnext = NULL;
while(ptmp)
{
p = ptmp;
ptmp = ptmp->pnext;
p->pnext = plink->phead;
plink->phead = p;
}
}
10、链表插入排序
void sort(Link_t *plink)
{
if(!plink->phead || !plink->phead->pnext)
return;
Link_node_t *p = plink->phead->pnext;
plink->phead->pnext = NULL;
Link_node_t *q = NULL;
Link_node_t *pins = NULL;
while(p)
{
pins = p;
p = p->pnext;
if(plink->phead->data >= pins->data)
{
pins->pnext = plink->phead;
plink->phead = pins;
}else
{
q = plink->phead;
while(q->pnext && q->pnext->data < pins->data)
{
q = q->pnext;
}
pins->pnext = q->pnext;
q->pnext = pins;
}
}
}