#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); }