单向链表的常用操作(C++模板实现)

来源:互联网 发布:域名第四级地址 编辑:程序博客网 时间:2024/05/16 04:43

最近担任我们学校C++课程的助教,发现这群98年左右的小孩编程能力实在是差,一个链表操作都能一个下午花去实现。话说,百度排前面的那些链表操作的代码写得也太不规范了吧。。。这里贴出一些上机实验时候关于链表操作的代码,希望那些孩子能百度到吧。。。
1,结构体

template <typename Object>struct Node{    Object data;    Node* next;    Node(const Object&d = Object(), Node*n = NULL) :data(d), next(n){}};

2,通过一个类实现

class singleList{public:    singleList(){ inti(); }    ~singleList(){ eraseList(head); }    singleList(const singleList & rhs)    {        eraseList(head);        init();        *this = rhs;    }    bool add(Object x)    {        if (contains(x))return false;        else        {            Node<Object>*ptr = new Node<Object>(x);            ptr->next = head->next;            head->next = ptr;            theSize++;        }        return true;    }    bool addSort(Object x)//有序添加    {        if (contains(x))return false;        else        {            Node<Object>*ptr = head->next;            Node<Object>*trailer = head;            while (ptr&&ptr->data < x)            {                trailer = ptr;                ptr = ptr->next;            }            trailer->next = new Node<Object>(x);            trailer->next->next = ptr;            theSize++;        }        return true;    }    bool remove(Object x)    {        if (!contains(x))return false;        else        {            Node<Object>*ptr = head->next;            Node<Object>*trailer;            while (ptr->data != x)            {                trailer = ptr;                ptr = ptr->next;            }            trailer->next = ptr->next;            delete ptr;            theSize--;        }        return true;    }    int size(){ return theSize; }    void print()    {        Node<Object>*ptr = head->next;        while (ptr != NULL)        {            printf("%d ", ptr->data);            ptr = ptr->next;        }        printf("\n");    }    bool contains(const Object & x)    {        Node<Object>*ptr = head->next;        while (ptr != NULL)        {            if (x == ptr->data)                return true;            else                ptr = ptr->next;        }        return false;    }    void init()    {        theSize = 0;        //Dwayne        head = new Node < Object > ;        head->next = NULL;    }    void eraseList(Node<Object>*h)    {        Node<Object>*ptr = h;        Node<Object>*nextPtr;        while (ptr != NULL)        {            nextPtr = ptr->next;            delete ptr;            ptr = nextPtr;        }    }private:    Node<Object>*head;    int theSize;};

原理没什么好说的,我博客里有一篇详细的分析,当然网上比我分析好的一大堆。我以后上课的时候把我博客的链接告诉那些孩子,这样也省了不少事情。
编程这事开始的时候效率先不提,最重要的是规范啊。多看大公司开源放出来的那些代码,模仿着去写。CSDN上也有不少人写得一手漂亮的代码,但是林子大了什么鸟都有了。

0 0