1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef int ElemType; 4 typedef struct DNode{ 5 ElemType data; 6 struct DNode *prior,*next; 7 }DNode,*DLinkList; 8 //双向链表头插法 9 DLinkList Dlist_head_insert(DLinkList &DL) 10 { 11 DNode *s;int x; 12 //带头结点的链表,不带头结点 13 DL=(DLinkList)malloc(sizeof(DNode)); 14 DL->next=NULL; 15 DL->prior=NULL; 16 //从标准输入读取数据 17 scanf("%d",&x); 18 //3 4 5 6 7 9999 19 while(x!=9999){ 20 //申请一个空间空间,强制类型转换 21 s=(DLinkList)malloc(sizeof(DNode)); 22 s->data=x; 23 s->next=DL->next; 24 //插入第一个结点时,不需要这一步操作 25 if(DL->next!=NULL){ 26 DL->next->prior=s; 27 } 28 s->prior=DL; 29 DL->next=s; 30 scanf("%d",&x);//读取标准输入 31 } 32 return DL; 33 } 34 //双向链表尾插法 35 DLinkList Dlist_tail_insert(DLinkList &DL) 36 { 37 int x; 38 //带头节点的链表 39 DL=(DLinkList)malloc(sizeof(DNode)); 40 DNode *s,*r=DL; 41 DL->prior=NULL; 42 //3 4 5 6 7 9999 43 scanf("%d",&x); 44 while(x!=9999){ 45 s=(DNode*)malloc(sizeof(DNode)); 46 s->data=x; 47 r->next=s; 48 s->prior=r; 49 //r指向新的表尾结点 50 r=s; 51 scanf("%d",&x); 52 } 53 //尾结点的next指针赋值为NULL 54 r->next=NULL; 55 return DL; 56 } 57 //按序号查找结点值 58 DNode *GetElem(DLinkList DL,int i) 59 { 60 int j=1; 61 DNode *p=DL->next; 62 if(i==0) return DL; 63 if(i<1) return NULL; 64 while(p&&j<i){ 65 p=p->next; 66 j++; 67 } 68 return p; 69 } 70 //新结点插入第i个位置 71 bool DListFrontInsert(DLinkList DL,int i,ElemType e) 72 { 73 DLinkList p=GetElem(DL,i-1); 74 if(NULL==p) return false; 75 //为新插入的结点申请空间 76 DLinkList s=(DLinkList)malloc(sizeof(DNode)); 77 s->data=e; 78 s->next=p->next; 79 p->next->prior=s; 80 s->prior=p; 81 p->next=s; 82 return true; 83 } 84 //删除第i个结点 85 bool DListDelete(DLinkList DL,int i) 86 { 87 DLinkList p=GetElem(DL,i-1); 88 if(NULL==p) return false; 89 DLinkList q; 90 q=p->next; 91 //删除的元素不存在 92 if(q==NULL) return false; 93 //断链 94 p->next=q->next; 95 if(q->next!=NULL){ 96 q->next->prior=p; 97 } 98 //释放对应结点的空间 99 free(q); 100 return true; 101 } 102 //链表打印 103 void PrintDList(DLinkList DL) 104 { 105 DL=DL->next; 106 while(DL!=NULL){ 107 printf("%3d",DL->data); 108 DL=DL->next; 109 } 110 printf(" "); 111 } 112 113 //双链表增删查 114 int main() 115 { 116 DLinkList DL; 117 DLinkList search; 118 //Dlist_head_insert(DL); 119 Dlist_tail_insert(DL); 120 //3 4 5 6 7 9999 121 PrintDList(DL); 122 search=GetElem(DL,2); 123 if(search!=NULL){ 124 printf("按序号查找成功 "); 125 printf("%3d ",search->data); 126 } 127 DListFrontInsert(DL,3,99); 128 PrintDList(DL); 129 DListDelete(DL,2); 130 PrintDList(DL); 131 system("pause"); 132 }