#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 ;
}