加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:09:52 所属栏目:百科 来源:网络整理
导读:C ++使用模板写的一个List templateclass 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

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; 
  } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读