赞
踩
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点
1.初始化
代码
- typedef struct DoubleLinkedNode{
- char data;
- struct DoubleLinkedNode *previous;
- struct DoubleLinkedNode *next;
- }DLNode, *DLNodePtr;
-
- DLNodePtr initLinkList(){
- DLNodePtr tempHeader = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
- tempHeader->data = '\0';
- tempHeader->previous = NULL;
- tempHeader->next = NULL;
- return tempHeader;
- }
2.打印链表
- void printList(DLNodePtr paraHeader){
- DLNodePtr p = paraHeader->next;
-
- while(p != NULL){
- printf("%c",p->data);
- p = p->next;
- }
-
- printf("\r\n");
- }
3.链表的插入
将p指向需要插入位置的前一位,新建一个q指向需要插入的链表,将q的后继指针指向p的后继指针指向的链表r,q的指针前驱指向p,p的后继指针指向q,如果r不为空,r的前驱指向q,q就成功地插入到了p和r的中间
- void insertElement(DLNodePtr paraHeader,char paraChar,int paraPosition){
- DLNodePtr p,q,r;
- p = paraHeader;
-
- for(int i = 0;i < paraPosition;i++){
- p = p->next;
- if(p == NULL){
- printf("The position %d is beyond the scope of the list.",paraPosition);
- return;
- }
- }
-
- q = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
- q->data = paraChar;
-
- r = p->next;
- q->next = p->next;
- q->previous = p;
- p->next = q;
-
- if(r != NULL){
- r->previous = q;
- }
- }

4.删除指定元素
将p指向头指针,将p依次向后移动,直到p的后继等于空,如果p的后继为空的话,就输出无法删除,或者p的后继中的元素是想要删除的元素,就将p的后继令为q,q中的元素就是想要删除的元素,r是q的后继,将p的后继指针指向r,如果r不为空的话,将r的前驱指向p,q中的元素就被删除了
- void deleteElement(DLNodePtr paraHeader,char paraChar){
- DLNodePtr p,q,r;
- p = paraHeader;
-
- while((p->next != NULL)&&(p->next->data != paraChar)){
- p = p->next;
- }
-
- if(p->next == NULL){
- printf("The char '%c' does not exist.\r\n",paraChar);
- return;
- }
-
- q = p->next;
- r = q->next;
- p->next = r;
-
- if(r != NULL){
- r->previous = p;
- }
-
- free(q);
- }

5.查找元素的位置
- void locateElement(DLNodePtr paraHeader,char paraChar){
- DLNodePtr p;
- int i=0;
- p = paraHeader;
-
- while((p->next != NULL)&&(p->next->data != paraChar)){
- p = p->next;
- i++;
- }
-
- if(p->next == NULL){
- printf("The char '%c' is Nofound\n",paraChar);
- }
- else{
- printf("Location of '%c' is '%d'\n",paraChar,i);
- }
- }

测试结果
双向链表可以找到前驱和后继,可进可退,但是相对单链表需要多分配一个指针存储空间
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。