C语言--双链表

来源:互联网 发布:js 对象作为参数 编辑:程序博客网 时间:2024/05/21 15:05

还是《程序员面试宝典》上的代码

#include <stdio.h>#include <stdlib.h>typedef struct student{    int data;    struct student *next;    struct student *pre;}dnode;// 建立双链表dnode *create(){    dnode *head,*p,*s;    int x,cycle = 1;    head = (dnode*)malloc(sizeof(dnode));    p = head;    while(cycle)    {        printf("\nPlease input the data:");        scanf("%d",&x);        if(x != 0)        {            s = (dnode*)malloc(sizeof(dnode));            s->data = x;            printf("%d\n",s->data);            p->next = s;            s->pre = p;            p = s;        }        else            cycle = 0;    }    p->next = NULL;    p = head;    head = head->next;    head->pre = NULL;    free(p); // 释放掉没有存数据的第一个节点    printf("\nHead data:%d\n",head->data);    return head;}// 求双链表长度,跟单链表一样int length(dnode *head){    int n = 0;    dnode *p;    p = head;    while(p != NULL)    {        p = p->next;        n++;    }    return n;}// 输出双链表,跟单链表一样void print(dnode *head){    dnode *p;    int n;    n = length(head);    printf("\nNow,These %d records are:\n",n);    p = head;    printf("NuLL <=> ");    while(p != NULL)    {        printf("%d <=> ",p->data);        p = p->next;    }    printf("NULL\n");}// 双链表删除节点dnode *del(dnode *head, int num){    dnode *p1,*p2;    p1 = head;    while(num != p1->data && p1->next != NULL)        p1 = p1->next;    if(num == p1->data)    {        if(p1 == head)             //删除的是链表头        {            head = head->next;            head->pre = NULL;        }        else if(p1->next == NULL)  //删除的是链表尾        {            p1->pre->next = NULL;        }        else                       // 删除的是链表中        {            p1->next->pre = p1->pre;            p1->pre->next = p1->next;        }        free(p1);    }    else    // 没有找到要删除的节点        printf("\n%d could not been found!",num);    return head;}// 双链表插入节点dnode *insert(dnode *head, int num){    dnode *p0,*p1;    p1 = head;    p0 = (dnode *)malloc(sizeof(dnode));    p0->data = num;    while(p0->data > p1->data && p1->next != NULL)        p1 = p1->next;    if(p0->data <= p1->data)    {        if(head == p1)  //插入链表头前        {            p0->pre = NULL;            p0->next = p1;            p1->pre = p0;            head = p0;        }        else            // 正常插入        {            p1->pre->next = p0;            p0->next  =p1;            p0->pre = p1->pre;            p1->pre = p0;        }    }    else               // num比链表中任何数都大,插入链表尾    {        p1->next = p0;        p0->pre = p1;        p0->next = NULL;    }    return head;}int main(){    dnode *stu_link;    int n,del_num,insert_num;    stu_link = create();    print(stu_link);    printf("\nPlease input a del num:");    scanf("%d",&del_num);    stu_link = del(stu_link,del_num);    print(stu_link);    printf("\nPlease input a insert num:");    scanf("%d",&insert_num);    stu_link = insert(stu_link,insert_num);    print(stu_link);    return 0;}

可能链表输出的样子有点问题,就这样看吧
只有一个节点的时候执行删除操作会崩溃,,