C++ 使用模板实现的一个List

c++使用模板写的一个List



template<class T>
class List
{
private:
    struct Node
    {
        T data;
        Node *next;
    };
    //head
    Node *head;
    //size
    int length;

    //process
    Node *p;

    //temp
    Node *q;
public:
    List()
    {
        head = NULL;
        length =  0;
        p = NULL;
    }
    void add(T t)
    {
        if(head == NULL)
        {
            q = new Node();
            q->data = t;
            q->next = NULL;
            length ++ ;
            head = q ;
            p = head;
        }
        else
        {
            q = new Node();
            q->data = t;
            q->next = NULL;
            length ++;
            p -> next = q;
            p = q;
        }
    }

    void remove(int n)
    {
        if(n >= length )
        {
            return;
        }
        length -- ;

        //删除头节点
        if(n == 0)
        {
            q = head ;
            head = head -> next;
            delete(q);
        }
        else
        {
            q = head;
            for(int i = 0 ; i < n-1 ; i++)
            {
                q = q -> next;
            }
            Node *t = q ->next;
            q->next = q->next ->next;
            delete(t);

        }

        //
        p = head;
        if (p != NULL)
        {
            while(p->next != NULL)
            {
                p = p->next;
            }
        }

    }

    int getSize()
    {
        return length;
    }

    int getLength()
    {
        return getSize();
    }

    T get(int n)
    {
        q = head;
        for (int i = 0 ;i < n ; i++)
        {
            q = q->next;
        }
        return q->data;
    }


};

调用方式如下

List<Stu>list;
	Stu stu1;
	Stu stu2;
	Stu stu3;
	stu1.username = "1";
	stu2.username = "2";
	stu3.username = "3";

	list.add(stu1);
	list.remove(0);
	list.add(stu2);
	list.add(stu3);

	for (int i = 0 ;i < list.getSize() ; i ++)
	{
		cout << list.get(i).username;
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值