本文主要是介绍双向链表基本知识,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、基本知识
1、两个指针,可以通过任意一个结点找到其前一个结点和后一个结点
二、基本操作
2.1、创建一个双向链表
Dlink_t *Create_doublelink()
{Dlink_t *pdoulink = malloc(sizeof(Dlink_t));if(pdoulink == NULL){return NULL;}pdoulink->phead = NULL;pdoulink->clen = 0;pthread_mutex_init(&(pdoulink->mutex),NULL);return pdoulink;
}
2.2、头插
nt push_doublelink(Dlink_t *dblink,Stu_t data)
{Dlink_node_t *dbnode = malloc(sizeof(Dlink_node_t));if(dbnode == NULL){perror("fail dbnode");return -1;}dbnode->data = data;dbnode->pperv = NULL;dbnode->pnext = NULL;if(is_empty_doublelink(dblink)){dblink->phead = dbnode;}else{dbnode->pnext = dblink->phead;dblink->phead->pperv = dbnode;dblink->phead = dbnode;}dblink->clen++;return 0;
}
2.3、尾插
int push_tail_doublelink(Dlink_t *dblink,Stu_t data)
{Dlink_node_t *dbnode = malloc(sizeof(Dlink_node_t));if(dbnode == NULL){perror("fail dbnode");return -1;}dbnode->data = data;dbnode->pperv = NULL;dbnode->pnext = NULL;Dlink_node_t *dnode = dblink->phead;if(is_empty_doublelink(dblink)){dblink->phead = dbnode;}else{while(dnode->pnext != NULL){dnode = dnode->pnext;}dnode->pnext = dbnode;dbnode->pperv = dnode;}
}
2.4、头删
int delete_head_doublelink(Dlink_t *dblink)
{if(is_empty_doublelink(dblink)){return -1;}Dlink_node_t *dbnode = dblink->phead;dblink->phead = dbnode->pnext;if(dbnode->pnext != NULL){dbnode->pnext->pperv = NULL;}free(dbnode);dblink->clen--;return 0;
}
2.5、尾删
int delete_tail_doublelink(Dlink_t *dblink)
{if(is_empty_doublelink(dblink)){return -1;}Dlink_node_t *dnode = dblink->phead;while(dnode->pnext != NULL){dnode = dnode->pnext;}if(donde->pperv != NULL){dnode->pperv->pnext = NULL;}free(dnode);dblink->clen--; return 0;
}
2.6、查询
Dlink_node_t *select_doublelink(Dlink_t *dblink,Stu_t data)
{if(is_empty_doublelink(dblink)){return NULL;}Dlink_node_t *dnode = dblink->phead;while(!strcmp(dnode->data.name,data.name)){dnode =dnode->pnext;}return dnode;
}
2.7、修改
}
Dlink_node_t *alter_doublelink(Dlink_t *dblink,Stu_t data,char *p)
{Dlink_node_t *q = select_doublelink(dblink,data);strcpy(q->data.name,p);return q;
}
2.8、销毁
int destory_doublelink(Dlink_t *dblink)
{if(is_empty_doublelink(dblink)){return -1;}Dlink_node_t *pnode = NULL;Dlink_node_t *p = NULL;while(dblink->phead != NULL){pnode = dblink->phead;dblink->phead = pnode->pnext;cc}free(dblink);return 0;
}
注意
在销毁的时候,要需注意在此用的是头删,我们需要考虑,头删的结点,的下一个结点是否存在,也就是说特列是只有一个结点,如果不考虑会造成指针越界
2.9、遍历
void doulink_for_each(DLink_t *pdoulink, int dir)
{if (is_empty_doulink(pdoulink))return;DLink_Node_t *p = pdoulink->phead;if (dir){while (p != NULL){printf("%d %s %d\n", p->data.id, p->data.name, p->data.score);p = p->pnext;}}else{while (p->pnext != NULL){p = p->pnext;}while (p != NULL){printf("%d %s %d\n", p->data.id, p->data.name, p->data.score);p = p->ppre;}}printf("\n");}
这篇关于双向链表基本知识的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!