关闭

双向链表的基本操作

标签: 链表
529人阅读 评论(0) 收藏 举报
分类:

#include <stdio.h>
#include <stdlib.h>
typedef struct List
{
     struct List *next,*prev;
     int item;
}List,*link;
link init();    //链表的初始化
link headinsert(); //每次在链表的头部添加新结点
link orderinsert();  //创建一个顺序的链表
link delete(link ,int);  //在链表中找到元素并删除
void show(link );

int main()
{
    List *p,*q,*L;
    printf("头插入法创建双向链表: \n");
    p = headinsert();
    show(p->next);
    printf("创建非降序双向链表: \n");
    q = orderinsert();
    show(q->next);
    printf("删除指定元素: \n");
    L = delete(q->next,20);
    show(L);
    return 0;
}

link init()
{
    List *st = malloc(sizeof(*st));
    st->next = NULL;
    st->prev = NULL;
    return st;
}

link headinsert()
{
    int x;
    List *st;
    st = init();
    while(scanf("%d",&x) != EOF)
    {
        st->item = x;
        List *p = malloc(sizeof(*p));
        st->prev = p;
        p->next = st;
        p->prev = NULL;
        st = p;
    }
    return st;
}

link orderinsert()
{
    int x;
    List *head,*st;
    st = init();
    head = st;
    while(scanf("%d",&x) != EOF)  //顺序输入数据
    {
        List *q = malloc(sizeof(*q));
        q->item = x;
        st->next = q;
        q->prev = st;
        q->next = NULL;
        st = st->next;
    }
    return head;

}

link delete(link st,int a)
{
    List *p,*t;
    int i = 0;
    p = st;
    while(st->next != NULL)
    {
        if(st->item == a)
        {
            st->prev->next = st->next;
            st->next->prev = st->prev;
            t = st->next;
            free(st);
            st = t;
            i++;
            break;
        }
        else
          st = st->next;
    }
    if(!i)
        printf("链表中没有此元素:%d!",a);
    return p;
}

void show(link st)
{
    int N = 0;
    while(st->next != NULL)
    {
        printf("%5d",st->item);
        st = st->next;
        N++;
    }
    printf("\n");
    printf("链表中元素个数为%d\n",N);
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5062次
    • 积分:231
    • 等级:
    • 排名:千里之外
    • 原创:19篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条