双向链表

双向链表的结点中有两个指针域:直接后继(next)和直接前驱(prior)。

空双向链表的判定:h->next = h->prior = h;

双向链表的结束判定:p->next = h。

 

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

#define OK 0
#define ERROR -1

typedef char elemtype;

typedef struct node {
    elemtype data;
    struct node *prior,*next;
}Dnode,*linklist;

linklist dulcreat()
{
    Dnode *h, *p, *t;
    elemtype ch;
    h = (linklist)malloc(sizeof(Dnode));
    h->next = h->prior = h;
    t = h;
    while((ch = getchar()) != '\n')
    {
        p = (linklist)malloc(sizeof(Dnode));
        p->data = ch;
        p->next = h;
        p->prior = t;
        h->prior = p;
        t->next = p;
        t = p;
    }
    if(h->next != h)
        return h;
    else
        return NULL;
}

//取元素
//读取单链表中第i个元素,1<=i<=length(h)
elemtype get(linklist h, int i)
{
    int j = 1;
    Dnode *p;
    p = h->next;
    while(p != h && j < i)//移动p,直到p为空,或者j < i
    {
        p = p->next;
        j++;
    }

    if((p != NULL) && j == i)
        return (p->data);
    if((p != NULL) && j == i)
        return (p->data);
    else
        return ERROR;
}
//删除元素
//删除i元素,并返回其值,1<=i<=length(h)  
elemtype delete(linklist h, int i)
{  
    int j = 1;
    elemtype e;
    Dnode *p, *q;
    p = h->next;
    while((p->next != h)&& j < i-1)
    {
        p = p->next;
        j++;
    }
    if((p->next != NULL) && j == i-1)
    {
        q = p->next;
        q->next->prior = p; //彼此之间的赋值不要弄错,可以先将未知的变量写出来。
        p->next = q->next;
        e = q->data;
        free(q);
        return e;
    }

    else
        return ERROR;
}
//插入元素
//第i个元素之前插入一个元素
int insert(Dnode *h, int i, elemtype x)
{
    Dnode *p, *s;
    p = h->next;
    int j = 1;
    while(p != h && j < i - 1)//寻找第i-1个结点
    {
        p = p->next;
        j++;
    }
    if(p && j == i- 1)
    {
        s = (Dnode *)malloc(sizeof(Dnode));
        s->next = p->next;//彼此之间的赋值不要弄错,可以先将未知的变量写出来。
        p->next = s;
        p->next->prior = s;
        s->prior = p;
        s->data = x;
        return OK;
    }
    else
        return ERROR;

}

//项目:循环链表
//时间:2011-9-30

#include"lklist_1.c"

int main()
{
    linklist taillist;
    int j = 1, count;
    taillist = dulcreat();
    printf("请输入所创建链表的元素个数:");
    scanf("%d", &count);
    printf("取单链表中第2个元素:");
    printf("%c\n",get(taillist, 2));
    printf("删除单链表中第3个元素:");
    printf("%c\n",delete(taillist, 3));
    printf("在链表中第3个元素之前插入c.\n");
    insert(taillist, 3, 'c');
    printf("依次输出单链表中的元素:");
    for(j = 1; j < count + 1; j++)
    {
        printf("%c",get(taillist, j));
    }
    printf("\n");
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值