雙向連結串列的應用
阿新 • • 發佈:2019-02-05
#include<stdio.h> #include<conio.h> #include<stdlib.h> typedef char DataType; typedef struct Node { DataType data; struct Node *prior; struct Node *next; }DListNode,*DLinkList; DListNode* GetElem(DLinkList head, int i); void PrintDList(DLinkList head); int CreateDList(DLinkList head, int n); int InsertDList(DLinkList henad, int i, char e); int InitDList(DLinkList *head) { *head = (DLinkList)malloc(sizeof(DListNode)); if (!head) return -1; (*head)->next = *head; //使頭結點的prior和next指標指向自己 (*head)->prior = *head; return 1; } int CreateDList(DLinkList head, int n) { DListNode *s, *q; int i; DataType e; q = head; for (i = 1; i <= n; i++) { printf("輸入%d個元素", i); e = getchar(); s = (DListNode*)malloc(sizeof(DListNode)); s->data = e;//將新生成的結點插入雙向迴圈連結串列 s->next = q->next; q->next = s; s->prior = q; head->prior = s;//這裡注意頭結點的prior指向新插入的結點 q = s; //q始終指向最後一個結點 getchar(); } return 1; } int InsertDList(DLinkList head, int i, DataType e) { DListNode *p, *s; p = GetElem(head, i); //查詢連結串列中第i個結點 if (!p) return 0; s = (DListNode*)malloc(sizeof(DListNode)); if (!s) return -1; s->data = e; //將s結點插入到雙向連結串列中 s->prior = p->prior; p->prior->next = s; s->next = p; p->prior = s; return 1; } DListNode* GetElem(DLinkList head ,int i) { DListNode *p; int j; p = head->next; j = 1; while (p != head && j < i) { p=p->next; j++; } if (p == head || j>i) //如果位置不整確,返回NULL return NULL; return p; } void main() { DLinkList h; int n, pos; char e; InitDList(&h); printf("輸入元素個數:"); scanf("%d", &n); getchar(); CreateDList(h, n); printf("連結串列中的元素:"); PrintDList(h); printf("請輸入元素以及位置:"); scanf("%c", &e); getchar(); scanf("%d", &pos); InsertDList(h, pos, e); printf("插入元素後連結串列中的元素:"); PrintDList(h); } void PrintDList(DLinkList head) //輸出迴圈雙鏈表中的每一個元素 { DListNode *p; p = head->next; while (p != head) { printf("%c", p->data); p = p->next; } printf("\n"); }