#include<stdio.h> #include<stdlib.h> typedef struct node* DNode; struct node { int data; DNode prior; //前面数据地址 DNode next; //后面数据地址 }; //创建双向链表 void CreatNode(DNode *head) { DNode s; //新节点指针 char e; (*head) = (DNode)malloc(sizeof(struct node));//头结点 (*head)->prior = (*head); //初始头结点的前驱和后驱都指向自己 (*head)->next = (*head); printf("输入数据\n"); scanf("%c", &e); while (e!=‘\n‘) { s = (DNode)malloc(sizeof(struct node)); //新节点分配空间 s->data = e; s->prior = (*head); //新节点的prior连前一个结点 s->next = (*head)->next; //新节点的next连后边结点 (*head)->next->prior = s; //后一个结点的prior连新结点 (*head)->next = s; //新节点前面的next连新结点 scanf("%c", &e); } } //向后遍历输出 void PrintList1(DNode L) { DNode p; p = L; p = p->next; while (p != L) { printf("%c", p->data); p = p->next; } printf("\n"); } //向前遍历输出 void PrintList2(DNode L) { DNode p; p = L->prior; while (p != L) { printf("%c", p->data); p = p->prior; } printf("\n"); } //查找第i处数据的地址 DNode FindPosition(DNode L,int i) { int j = 0; DNode p = L; while (p->next != L&&j < i) { p = p->next; j++; } return p; } //插入 void InsertList(DNode L) { DNode s,p; //s为新结点 p为新节点前一个结点 int i; char e; printf("在第几处插入:\n"); scanf("%d", &i); getchar(); printf("插入什么数据:\n"); scanf("%c", &e); p = FindPosition(L, i-1); //新节点前一个结点地址 s = (DNode)malloc(sizeof(struct node));//申请新节点空间 s->data = e; s->prior = p; //新节点的prior连上前一个结点 s->next = p->next; //新节点的next连上后一个结点 p->next->prior = s; //新节点后的结点的prior连上新结点 p->next = s; //新节点前的结点的next连上新结点 } //删除 void DeleteList(DNode L){ DNode s,p; //s为新结点 p为要删除的结点 int i; printf("删除第几处的数据:\n"); scanf("%d", &i); p = FindPosition(L, i); //要删除结点的地址 p->prior->next = p->next; //要删除的结点的前一个结点的next,连上要删结点后的结点 p->next->prior = p->prior;//要删除结点的后一个结点的prior,连上要删结点的前一个结点 free(p); } int main() { DNode list; CreatNode(&list); //PrintList1(list); PrintList2(list); InsertList(list); PrintList2(list); DeleteList(list); PrintList2(list); }