#include#include typedef int Elemtype; typedef struct DNode//双链表结点类型 12个字节 { Elemtype data;//数据域 struct DNode *prior;//前驱指针 struct DNode *next;//后继指针 } DLNode,*DlinkList; //头插法建立双链表 DlinkList DList_head_Insert(DlinkList &DL) { DLNode *s; int x; DL=(DlinkList)malloc(sizeof(DLNode));//带头结点的链表,DL头结点 DL->next=NULL;//L->data里面没有东西 DL->prior=NULL; scanf("%d",&x);//从标准输入读取东西 //3 4 5 6 7 9999 while(x!=9999) { s=(DLNode*)malloc(sizeof(DLNode));//申请一个新空间给s,强制类型转换 s->data=x;//把读取到的值,给新空间的data成员 s->next=DL->next;//让新结点的next指针指向链表第一个元素 (第一个放我们数据的元素) if(DL->next!=NULL) { DL->next->prior=s ; } s->prior=DL; DL->next=s; scanf("%d",&x);//从标准输入读取东西 } return DL; } //尾插法新建双向链表; DlinkList DList_tail_Insert (DlinkList &DL) //list_Tail { int x; DL=(DlinkList)malloc(sizeof(DLNode));//带头结点的链表 DLNode* s; DLNode*r=DL;//r代表链表表尾结点,指向链表尾部 ,初始l相当于r DL->prior=NULL; //输入3 4 5 6 7 9999 scanf("%d",&x); while(x!=9999) { s=(DLNode*)malloc(sizeof(DLNode)); s->data=x;//把读取到的值,给新空间的data成员 r->next=s;//让尾部结点指向新结点 s->prior=r; r=s;//r指向新的表尾结点 scanf("%d",&x); } r->next=NULL;//尾结点next指针赋值为NULL return DL; } //查找对应位置的值 DlinkList GetElem(DlinkList DL,int i) { int j = 1; DLNode*p=DL->next;//让P指向第一个结点 if(i ==0) { return DL;//返回头结点 } if(i<1) { return NULL;//i是负值就返回空 } while(p&&jnext; j++; } return p; } //新结点插入第i个位置 bool DListFront_Insert(DlinkList &DL,int i,int e) { DLNode* p=GetElem(DL,i-1);//拿到插入位置前一个位置地址 if(p==NULL) { return false;//i不对 } DLNode*s=(DLNode*)malloc(sizeof(DLNode)); s->data=e; s->next=p->next; p->next->prior=s; s->prior=p; p->next=s; return true; } //删除第i个位置元素 bool DListDelete(DlinkList &DL,int i) { DLNode*p=GetElem(DL,i-1);//获得第i个位置前一个结点地址 if(NULL==p)//要删除的位置不存在 { return false; } DLNode* q; q=p->next;//q指针指向第i个结点 if(NULL==q)//删除的元素不存在 { return false; } p->next=q->next;//断链 if(q->next!=NULL)//q->next为NULLz则删除的是最后一个结点 { q->next->prior=q; } free(q);//释放对应结点空间 q = NULL;// return true; } void PrintDList(DlinkList DL) { DL=DL->next; while (DL!=NULL) { printf("%-4d",DL->data); DL=DL->next; } printf("n"); } int main() { DlinkList DL; DlinkList search; DList_head_Insert(DL); //DList_tail_Insert(DL); //3 4 5 6 7 9999 PrintDList(DL); search=GetElem(DL,2); if(search!=NULL) { printf("按序第二位查找成功n"); printf("%dn",search->data);//查找链表第二个结点元素值 } DListFront_Insert(DL,3,99); PrintDList(DL); DListDelete(DL,2); PrintDList(DL); return 0; }



