循环链表的实现 (circularly linked list)

节点,和circularly list类C_list:
typedef struct Node{
    int key;
    struct Node *next;
}Node,*pNode;

typedef struct C_list{
    pNode lastNode;
    C_list();
    void insertAfter(Node &nod, Node &x);
    void insertAfter(C_list &lis, Node &x);
    void insertBeginning(C_list &lis, Node &x);
}C_list;


C_list::C_list(){
    this->lastNode = NULL;
}

void C_list::insertAfter(Node &nod, Node &x){
    if(&nod == NULL){
        x.next = &x;
    }
    else{
        x.next = nod.next;
        nod.next = &x;
    }
}

void C_list::insertAfter(C_list &lis, Node &x){
    insertAfter(*lis.lastNode, x);
    lis.lastNode = &x;
}

void C_list::insertBeginning(C_list &lis, Node &x){
    insertAfter(*lis.lastNode, x);
}


测试:

void test(){
    Node x = {2,NULL}, y = {7,NULL}, z = {3,NULL};
    C_list lis;
    cout<<lis.lastNode<<endl; //NULL = 0

    lis.insertAfter(lis, x);
    lis.insertAfter(lis, y);
    lis.insertAfter(lis, z);
    Node temp = *lis.lastNode;
    for(int i = 0; i < 3; i++){
        cout<<temp.next->key<<" ";
        temp = *temp.next;
    }// 2 7 3
    cout<<endl;

    Node a = {1,NULL}, b = {5,NULL};
    lis.insertBeginning(lis, a);
    lis.insertBeginning(lis, b);

    pNode nod = lis.lastNode->next;
    do{
        cout<<nod->key<<" ";
        cout<<nod<<endl;
        nod = nod->next;
    }while(nod != lis.lastNode->next);
    //5 1 2 7 3
}

结果:




阅读更多
个人分类: 算法 c++容器
上一篇用list实现桶排序
下一篇双链表 double linked list
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭