1.4雙向連結串列表示與實現
阿新 • • 發佈:2020-12-14
1.4雙向連結串列表示與實現
1、雙向連結串列是指連結串列中每個結點都有兩個指標域,一個指向後繼結點,一個指向前驅結點。prior和next.
2、雙向連結串列也分帶頭和不帶頭,帶頭操作更加方便。雙向連結串列也有迴圈結構,稱雙向迴圈連結串列。
3、帶頭雙向迴圈連結串列的判空條件為head->prior==head或head->next==head;
程式碼實現:
DLinkList.h
#pragma once #include <stdio.h> #include <stdlib.h> typedef int DataType; typedef struct Node { DataType data; struct Node* prior, * next; //p為前指標,q為後指標 }DListNode,*DListLink; //插入函式 int InsertDList(DListLink head,int i,DataType e) { DListNode* p, * s; int j=0; p = head->next; while (p!=head && j<i) { p = p->next; j++; } if (j!=i) { printf("插入位置不正確"); return 0; } s = (DListNode *)malloc(sizeof(DListNode)); if (s==NULL) { return -1; } s->data = e; s->prior = p->prior; p->prior->next = s; s->next = p; p->prior = s; return 1; } //刪除函式 int DeleteDList(DListLink head, int i, DataType *e) { DListNode* p, * s; int j = 0; p = head->next; while (p != head && j < i) { p = p->next; j++; } if (j != i) { printf("輸入位置不正確"); return 0; } p->prior->next = p->next; p->next->prior = p->prior; free(p); return 1; } //初始化函式 int InitDList(DListLink *head) { *head = (DListLink)malloc(sizeof(DListNode)); if (!head) return -1; (*head)->next = *head; (*head)->prior = *head; return 1; } //建立迴圈單鏈表 int CreateDList(DListLink head,int n) { DListNode* s, * q; DataType e; q = head; for (int 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; q = s; getchar(); } return 1; } //輸出函式 void PrintDList(DListLink head) { DListNode* p; p = head->next; while (p!=head) { printf("%c",p->data); p = p->next; } printf("\n"); }
test.c
#include <stdio.h> #include <stdlib.h> #include "DLinkList.h" void main() { DListLink h; int n; int pos; char e; InitDList(&h); printf("輸入元素的個數:"); scanf_s("%d",&n); getchar(); CreateDList(h, n); printf("連結串列中的元素:"); PrintDList(h); printf("請輸入插入的元素:"); scanf_s("%c",&e); getchar(); printf("請輸入插入元素的位置:"); scanf_s("%d", &pos); InsertDList(h, pos, e); printf("插入後連結串列中的元素:"); PrintDList(h); }