数据结构—循环链表

List.h头文件源代码

#ifndef _LIST_H_

#define _LIST_H_

//迭代器的前置声明

template

class ListInterator;

//链表类的前置声明

template

class List;

 

template

class ListNode    //节点类

{

    friend class List;

    friend class ListInterator;

    private:

        Type data;    //节点存储数据

        ListNode* link;    //指向下一个节点的指针

        ListNode(Type);        //节点的构造函数

        ListNode(){};

};

 

template

class List    //链表类

{

    friend class ListInterator;

    public:

        List()    //链表的构造函数

        {

            first=new ListNode;

            first->link=first;

        }

        void Insert(Type);    //插入节点

        void Delete(Type);    //删除节点

    private:

    ListNode* first;

};

 

 

template

class ListInterator    //链表迭代器类

{

    public:

        ListInterator(const List& l):list(l),current(l.first->link){};

        bool NotNull();    //判断当前节点是否为空

        bool NextNotNull();    //当前节点的下一个节点是否为空

        Type* First();

        Type* Next();

    private:

        const List& list;

        ListNode* current;

};

 

//节点构造函数的实现

template

ListNode::ListNode(Type elemnt)

{

    data=elemnt;

    link=0;

}

 

//链表类插入函数的实现

template

void List::Insert(Type k)

{

    ListNode* newnode=new ListNode(k);

    newnode->link=first->link;    //原来的头指针后移

    first->link=newnode;        //插入的新的节点指针成为头指针

    

}

 

template

void List::Delete(Type k)

{

    ListNode* previous=first;    //保存前一个节点

    ListNode* current;    //循环指针

    for(current=first->link;(current!=first)&&current->data!=k;previous=current,current=current->link)

    {

        //空循环

    }

    if(current!=first)

    {

            previous->link=current;

            delete current;

    }

 

}

 

 

template

bool ListInterator::NotNull()

{

    if(current!=list.first)

        return true;

    else

        return false;

}

 

template

bool ListInterator::NextNotNull()

{

    if(current->link!=list.first)

        return true;

    else

        return false;

}

 

template

Type* ListInterator::First()

{

    if(current!=list.first)

        return &current->data;

    else

        return 0;

}

 

template

Type* ListInterator::Next()

{

        current=current->link;

        if(current==list.first)

            current=current->link;

        return &current->data;

}

#endif

主程序源代码:

#include

#include"List.h"

 

using namespace std;

 

int main()

{

    List intList;

    intList.Insert(5);

    intList.Insert(15);

    intList.Insert(25);

    intList.Insert(35);

    ListInterator iter(intList);

    cout<<*iter.First()<<endl;

    cout<<*iter.Next()<<endl;

    cout<<*iter.Next()<<endl;

    cout<<*iter.Next()<<endl;

    cout<<*iter.Next()<<endl;    

    cout<<*iter.Next()<<endl;

    cout<<*iter.Next()<<endl;

    cout<<*iter.Next()<<endl;

    cout<<*iter.Next()<<endl;    

    return 0;

}

运行结果:

 

数据结构—循环链表

posted @ 2016-04-27 11:13  硫酸亚铜  阅读(149)  评论(0编辑  收藏  举报