我想创建一个双向链表,它使用异或运算函数构造节点的地址,使得节点的地址是之前两个节点的地址的异或。
在我的代码中,函数
PrintListBackwards()
确实正常运行,它显示列表中的最后一个元素两次然后停止,就好像 while 循环没有停止一样。
如果我的列表是这样的:
A->B->C
我知道如果我想从 A 到 C,我可以计算节点 C 的地址,所以:
地址(A)^地址(B)=地址(C)
所以如果我想从 C 到 A 我只需要与地址(B)进行异或运算,右侧的地址(B)将取消,我将得到
地址(A)=地址(B)^地址(C)。
这是我的代码:
typedef struct NodeT
{
int number;
struct NodeT *next;
} NodeT;
typedef struct LisT
{
unsigned int size;
struct NodeT *first;
struct NodeT *last;
} LisT;
NodeT* ConstructAddress(NodeT *x,NodeT *y)
{
return (NodeT *) ((uintptr_t)(x)^(uintptr_t)(y));
}
NodeT *FindElemInList(LisT *listptr,int key)
{
NodeT *head=listptr->first;
if(head==NULL)
return NULL;
while(NULL!=head && head->number!=key)
head=head->next;
if(head==NULL)
return NULL;
return head;
}
void InsertAtStart(LisT *listptr,int number)
{
NodeT *head=listptr->first;
NodeT *temp=(NodeT *)malloc(sizeof(NodeT));
temp->number=number;
temp->next=ConstructAddress(head,NULL);
if(head==NULL)
{
head=temp;
listptr->first=temp;
listptr->last=temp;
listptr->size++;
return;
}
NodeT *ptr=ConstructAddress(head->next,NULL);
head->next=ConstructAddress(temp,ptr);
listptr->first=temp;
listptr->size++;
}
void InsertAtEnd(LisT *listptr,int number)
{
NodeT *tail=listptr->last;
NodeT *prev=ConstructAddress(tail,tail->next);
NodeT *temp=(NodeT *)malloc(sizeof(NodeT));
temp->number=number;
temp->next=ConstructAddress(tail,NULL);
if(tail==NULL)
{
tail=temp;
listptr->first=temp;
listptr->last=temp;
listptr->size++;
return;
}
NodeT *ptr=ConstructAddress(tail,prev);
tail->next=ConstructAddress(temp,ptr);
listptr->last=temp;
listptr->size++;
}
void PrintList(LisT *listptr)
{
NodeT *curr=listptr->first;
NodeT *prev=NULL;
NodeT *next;
printf("%d",curr->number);
next=ConstructAddress(prev,curr->next);
prev=curr;
curr=next;
while(curr!=NULL)
{
printf("->%d",curr->number);
next=ConstructAddress(prev,curr->next);
prev=curr;
curr=next;
}
printf("\n");
}
void PrintListBackward(LisT *listptr)
{
NodeT *curr=listptr->last;
NodeT *prev=NULL;
printf("%d",curr->number);
NodeT *next=ConstructAddress(curr->next,curr);
while(curr!=listptr->first)
{
prev=curr;
curr=next;
next=ConstructAddress(curr->next,curr);
printf("<-%d",curr->number);
}
}
如果有人注意到我代码中的问题,请向我指出,我看了一些关于这个主题的视频,并阅读了我老师提供的文档。