单向链表
//链表的创建
Link_t *create_link()
{Link_t *plink = malloc(sizeof(Link_t));if(NULL == plink){perror("fail plink");return NULL;}plink->phead = NULL;plink->clen = 0;return plink;
}
//头插
int push_link_head(Link_t *plink, DataType data)
{Link_Node_t *pnode = malloc(sizeof(Link_Node_t));if(NULL == pnode){perror("fail malloc");return -1;}pnode->data = data;pnode->pnext = NULL;pnode->pnext = plink->phead;plink->phead = pnode;plink->clen++;return 0;
}
//尾插
int push_link_end(Link_t *plink, DataType data)
{Link_Node_t *p = plink->phead;if(p == NULL){push_link_head(plink, data);}else{while(p->pnext != NULL){p = p->pnext;}Link_Node_t *pnode = malloc(sizeof(Link_Node_t));if(NULL == pnode){perror("fail pnode");return -1;}p->pnext = pnode;pnode->pnext = NULL;pnode->data = data;plink->clen++;}return 0;
}
//头删
int push_head_pop(Link_t *plink)
{Link_Node_t *p = plink->phead;if(p == NULL){return 0;}else{plink->phead = p->pnext;free(p);}plink->clen--;return 1;
}
//尾删
int push_end_pop(Link_t *plink)
{Link_Node_t *p = plink->phead;if(p == NULL){return 0;}else if(p->pnext == NULL){push_head_pop(plink);}else{while(p->pnext->pnext != NULL){p = p->pnext;}free(p->pnext);p->pnext = NULL;plink->clen--;}return 1;
}
在进行排序时,一次遍历结束指针指到了结尾,要重新把指针归到头节点,否则排序不成功。
//排序
void push_sort(Link_t *plink)
{if(1 == plink->clen || plink->phead == NULL){return;}Link_Node_t *pinsert = NULL;Link_Node_t *ptmp = plink->phead->pnext;plink->phead->pnext = NULL;while(ptmp != NULL){Link_Node_t *p = plink->phead;pinsert = ptmp;ptmp = ptmp->pnext;if(p->data > pinsert->data){pinsert->pnext = plink->phead;plink->phead = pinsert;}else{while(p->pnext != NULL && p->pnext->data < pinsert->data){p = p->pnext;}pinsert->pnext = p->pnext;p->pnext = pinsert;}}
}