和单链表类似,双链表也由头指针head唯一确定,增加头结点也能使双链表上的某些运算变得方便,将头结点和尾结点链接起来也能构成循环链表。双链表结构是一种对称结构,既有前向链又有后向链,这使得插入和删除操作都很方便。
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct dnode
{
datatype data;
struct dnode *prior,*next;
}dlinklist;
/*创建双链表*/
dlinklist *CreateList(){
char ch;
dlinklist *head,*temp,*rear;
head = (dlinklist*)malloc(sizeof(dlinklist));
rear = head;
rear->prior = head;
ch = getchar();
while (ch != '$')
{
temp = (dlinklist*)malloc(sizeof(dlinklist));
temp ->data = ch;
temp ->prior = rear;
rear ->next = temp;
rear = temp;
ch = getchar();
}
rear->next = NULL;
return head;
}
/*双链表的前插操作,在带头结点的双链表中,将值为x的新结点插入*p之前*/
void DIsertBefore(dlinklist *p,datatype x){
dlinklist *temp;
temp = (dlinklist*)malloc(sizeof(dlinklist));
temp ->data = x;
temp->prior = p->prior;
temp->next = p;
p->prior->next = temp;
p->prior = temp;
}
/*双链表上删除自身的操作*/
void DeleteNode(dlinklist *p){
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
}