鱼C论坛

 找回密码
 立即注册
查看: 3439|回复: 0

类模板List1使用

[复制链接]
发表于 2012-9-3 18:03:44 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include<iostream>
using namespace std;
template<class T>
class list1
{
public:
        list1();
        void add(T&);
        void remove(T&);
        void printlist();
        ~list1();
protected:
        struct node
        {
                node *pnext;
                T data;
        };
        node *phead;
};
template<class T>
list1<T>::list1()
{
        phead=NULL;
}
template<class T>
void list1<T>::add(T &t)
{
        node *temp=new node;
        temp->data=t;
        temp->pnext=phead;
        phead=temp;
}
template<class T>
void list1<T>::remove(T &t)
{
        node *q=0;
        if((phead->data)==t)
        {
                q=phead;
                phead=phead->pnext;
        }
        else
        {
                for(node *p=phead;p->pnext;p=p->pnext)
                        if((p->pnext->data)==t)
                        {
                                q=p->pnext;
                                p->pnext=q->pnext;
                                break;
                        }
        }
        if(q)
        {
                delete q;
        }
}
template<class T>
void list1<T>::printlist()
{
        for(node *p=phead;p;p=p->pnext)
        {
                cout<<(p->data)<<" ";
        }
        cout<<endl;
}
template<class T>
list1<T>::list1()
{
        node *p;
        while(phead!=NULL)
        {
                p=phead;
                phead=phead->pnext;
                delete p;
        }
}
int main()
{
        list1<int>intlist;
        int a;
        for(int i=0;i<10;i++)
        {
                intlist.add(i);
        }
        cout<<"the int list is :";
        intlist.printlist();
        cout<<"please input a integer to remove:";
        cin>>a;
        intlist.remove(a);
        cout<<"after removed :"<<endl;
        cout<<"the int list is :";
        intlist.printlist();
        return 0;
}//不知道哪里错了,麻烦指点下。

小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-14 23:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表