双向链表的基本操作

来源:互联网 发布:网络教学系统uml 编辑:程序博客网 时间:2024/06/15 01:51
#include <stdio.h>#include <stdlib.h>struct DLinklist{    char data;    struct DLinklist *prior,*next;};DLinklist * createDL(){    DLinklist * head,*p;    char x;    head = (DLinklist *)malloc(sizeof(DLinklist));    head->next = head;    head->prior = head;    printf("please input the values!\n");    scanf("%c",&x);    while(x != '\n'){        p = (DLinklist *)malloc(sizeof(DLinklist));        p->data = x;        p->next = head->next;        p->prior = head;        head->next->prior = p;        head->next = p;             scanf("%c",&x);    }    return head;}DLinklist * getLocation(DLinklist * head,int i){    DLinklist * p = head;    int j=0;    while(p->next != head && j<i){        j++;        p = p->next;    }    if(p->next != head){        return p;    }else{        return NULL;    }}void insertDL(DLinklist * head,int i,char x){    DLinklist * p,*q;    p = getLocation(head,i-1);    if(p == NULL){        printf("the location doesn't exist!\n");    }else{        q=(DLinklist *)malloc(sizeof(DLinklist));           q->data = x;        q->next = p->next;        q->prior = p;        p->next->prior = q;        p->next = q;    }}void delDL(DLinklist * head,int i){    DLinklist * p;    p = getLocation(head,i);    if(p == NULL){        printf("the location doesn't exist!\n");    }else{        p->prior->next = p->next;        p->next->prior = p->prior;        free(p);    }}void printDL(DLinklist * head){    DLinklist * p;    p = head->next;    while(p != head){        printf("%c",p->data);        p = p->next;    }}int main(){    DLinklist * head,*p;    head = createDL();    printDL(head);    printf("\n");    p = getLocation(head,3);    if(p == NULL){        printf("the location doesn't exist!\n");    }else{        printf("%c",p->data);    }    printf("\n");    printf("after insert:\n");    insertDL(head,5,'a');    printDL(head);    printf("\n\n");    printf("after delete:\n");    delDL(head,4);    printDL(head);    printf("\n");    return 0;}     
0 0
原创粉丝点击