c語言實現雙向連結串列的基本操作
阿新 • • 發佈:2019-02-06
雙向連結串列,又可以稱為雙向迴圈連結串列。
雙向連結串列中插入刪除操作的詳細解析可以看這篇文章:雙鏈表,下面是個人寫的簡單程式碼,僅供參考。
#include<stdio.h> #include<stdlib.h> struct DulNode { int data; DulNode *prior; DulNode *next; }; //初始化空的頭結點 DulNode *InitDulNode() { DulNode *head; head = (DulNode*)malloc(sizeof(DulNode)); head->next = head; head->prior = head; return head; } //初始化資料 void InitdulList(DulNode *dulList) { DulNode *node; node = (DulNode*)malloc(sizeof(DulNode)); printf("輸入資料:"); scanf("%d",&node->data); //新節點的next指標域 node->next = dulList->next; dulList->next->prior = node; node->prior = dulList; dulList->next = node; } void Insert(DulNode *dulList) { DulNode *node; node = (DulNode*)malloc(sizeof(DulNode)); printf("輸入插入資料:"); scanf("%d",&node->data); printf("輸入插入位置:"); int position; scanf("%d",&position); int i=0; dulList = dulList->next; while(i < position-1 && dulList != NULL) { i++; dulList = dulList->next; } node->next = dulList->next; dulList->next->prior = node; dulList->next = node; node->prior = dulList; } void Delete(DulNode *dulList) { printf("輸入刪除位置:"); int position; scanf("%d",&position); int i=0; //dulList = dulList->next; while(i < position-1 && dulList->next != NULL) { i++; dulList = dulList->next; } DulNode *dul = dulList->next; dulList->next = dul->next; dul->next->prior = dulList; printf("刪除的資料為:%d\n",dul->data); free(dul); } void Output(DulNode *dulList) { DulNode *temp = dulList;//temp指向尾節點 while(dulList->prior != temp) { printf("資料為:%d\n",dulList->prior->data); //printf("資料為:%d\n",dulList->next->next->next->data); dulList = dulList->prior; } } void menu() { printf("****************\n"); printf(" * 1--初始化\n"); printf(" * 2--新增資料\n"); printf(" * 3--刪除資料\n"); printf(" * 4--檢視資料\n"); printf(" * 0--退出\n"); printf("****************\n"); } int main() { DulNode *dulList,*p; p = dulList = InitDulNode(); int i = 0; int choose; do { menu(); printf("輸入您的選擇:"); scanf("%d",&choose); getchar(); switch(choose) { case 1: //相當於每次都在第一個位置插入 while(i<3) { InitdulList(p); //p = p->next;//相當於每次都在最後一個位置插入 i++; } break; case 2: Insert(dulList); break; case 3: Delete(dulList); break; case 4: Output(dulList); break; case 0: break; } }while(choose != 0); return 0; }