双向循环链表的插入和删除
(a)为删除,(b)为插入
双向循环链表实则为一个环状,因此插入、删除代码对任一位置的节点都适用
代码如下
#define OK 1 #define ERROR 0 typedef int Status; typedef struct DuLNode { ElelmentType data; struct DuLNode *prior; struct DuLNode *next; } * DuLinkedList; DuLinkedList getElemp(DuLinkedList &L,int i) { DuLinkedList p = L; for(int j = i; j >0; j--) { p = p->next; } return p; } /*在双链表第i个位置之前插入节点*/ Status insert_DuLinkedList(DuLinkedList &L,int i,ElelmentType e) { DuLinkedList p,s; if(!(p = getElemp(L,i)))//用于取得第i个位置的指针 return ERROR; if(!(s = (DuLinkedList)malloc(sizeof(struct DuLNode)))) return ERROR; s->data = e; s->prior = p->prior; s->prior->next = s; s->next = p; p->prior = s; return OK; } /*在双链表上删除元素*/ ElelmentType Delete_Dulist(DuLinkedList &L, int i, ElelmentType &e) { DuLinkedList p; if(!(p = getElemp(L,i))) return ERROR; e = p->data; p->prior->next = p-next; p->next->prior = p->prior; free(p); return e; }
需要注意的是,该双向循环链表默认有一个头节点,"第i个位置"是不包含头节点的,第一个位置,表示该链表第一个拥有实际意义的节点