CLRS 10.28

#line 1 "CLRS 10.2-8,非循环双链表"
#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
    int data;
    unsigned int np; //指针是32位
}Node ,*PNode;
typedef struct
{
    PNode head;
}List,*PList;

PList init_list()//初始化
{
    PList p;
    p=(PList)malloc(sizeof(List));
    if(p)
    {
        p->head=(PNode)malloc(sizeof(Node));
        if(p->head)
        {
            // p->prev=NULL;
            // p->next=NULL;
            // p->np=p->prev ^ p->next=NULL;
            p->head->np=0;
        }
    }
    return p;
}

void insert_list(PList L,int value)
{
    //总在head节点后面插入
    //假设现在是
    /*
         head->B   
         我们要插入新节点A到head后面去,head->A->B
         现在的prev和next是
         head->prev=0  一直没变
         head->next=A   由原来head->next=B变成head->next=A
         A->prev=head     由原来0变成head
         A->next=B          由原来0变成B
         B->prev=A          由原来B->prev=A变成B->prev=A
         B->next=??          没发生变化

        因为A->np=A->prev ^ A->next ,由异或的性质可得
        A->prev = A->np ^ A->next
        A->next = A->np ^ A->prev
    */

    /*
         先改变A的
         A->prev=head
         A->next=head->next
         所以A->np=head ^ head->next
         由head->next=head->np ^ head->prev 并且 head->prev=null(0)
         所以head->next=head->np
         A->np=head ^ head->next=head ^ head->np
     */
    PNode A;
    A=(PNode)malloc(sizeof(Node));
    A->data=value;
    A->np=(unsigned int)(L->head) ^ (L->head->np);


    /*
         原来的B地址是head->next=head->np ^ head->prev=head->np

         下面改B的
         B->next没变
         B->prev=A
         原来 B->next=B->np ^ B->prev,B->prev=head
         所以 新的B->np=B->next ^ B->prev = B->np ^ head ^ A
     */
    PNode p=(PNode)(L->head->np);
    if(p)//B存在的话
    {
            unsigned int temp=p->np;
            temp=temp ^ (unsigned int)A ^ (unsigned int)(L->head);
            p->np=temp;
    }

    /*
         下面改head的
            head->prev=0
            head->np=head->next=A
     */
    L->head->np=(unsigned int)A;

}

void print(PList L)
{
    unsigned int  p,q,r;

    p=L->head->np;q=(unsigned int)L->head;r=q;
    while(p!=0)
    {
        printf("%d ",((PNode)p)->data);
        r=((PNode)p)->np ^ q;  //新的p->next
        q=p;
        p=r;
    }
}
    
void free_list(PList L)
{
    unsigned int  p,q,r;

    p=L->head->np;
    q=(unsigned int)(L->head);
    r=(unsigned int)(L->head);
    while(p != 0)//非循环链表
    {
        r=((PNode)p)->np ^ q; //p->next
        q=p;
        p=r;
        free((PNode)q);
    }
    free(L->head);
}

void main()
{
    PList p;
    p=init_list();
    int i;
    for(i=0;i<10;i++)
        insert_list(p,i);
    print(p);
    free_list(p);
}



原文地址:https://www.cnblogs.com/buxianghe/p/2975663.html