双向链表的创建删除

#include "stdlib.h"
#include "stdio.h"
typedef struct tlistnode
{
    int a;
    struct tlistnode *prior;
    struct tlistnode *next;
} tlistnode;
tlistnode *head;//全局变量,双向链表首地址
tlistnode *create(int i)//创建节点数为i的双向链表,节点内容为i
{
    tlistnode *head,*p1,*p2;
    head=(tlistnode*)malloc(sizeof(tlistnode));//
    head->a=i;//
    head->next=head->prior=head;//空链表构成,前项后项均指向自己
    p1=p2=head;
    i--;
    while(i)
    {
        p1=(tlistnode*)malloc(sizeof(tlistnode));
        p1->a=i;
        p2->next=p1;
        p1->prior=p2;
        p1->next=head;
        p2=p1;
        i--;
    }
    head->prior=p1;//将链表头前项地址置为最后一项
    return head;
}

void delete_tlistnode(tlistnode *deletehead,int i)//删除第i个元素,i为正值为正数第i个,i为负值为倒数第i个
{
    int n=i;
    if(i>0)
    {
        while(n-1)//从一计数
        {
            deletehead=deletehead->next;
            n--;
        }

        deletehead->prior->next=deletehead->next;
        deletehead->next->prior=deletehead->prior;

        if(i==1) head=deletehead->next;//考虑首地址被删除的情况,首地址后移
        else free(deletehead);




    }
    else
    {
        i=abs(i);
        while(i)
        {
            deletehead=deletehead->prior;
            i--;
        }
        deletehead->prior->next=deletehead->next;
        deletehead->next->prior=deletehead->prior;
        free(deletehead);
        deletehead=NULL;
    }


}
int main()
{
    int i,n;
    head=create(7);
    delete_tlistnode(head,-3);
    for(i=6; i; i--)
    {
        printf("%d ",head->a);
        head=head->next;
    }
    return ;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值