带模板类的C++链表

头文件list.h:

#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED

template 
struct NODE
{
    T data;
    struct NODE *next;
};

template 
class nodelist
{
private:
    NODE *head;
public:
    nodelist(){ head = NULL; };
    ~nodelist();
    void clearlist();//清空链表
    int listlength();//链表长度
    void pushback(T data);//在链表末尾加入数据
    void printlist();//打印链表
    void searchlist(T data);//搜索
};

template 
nodelist::~nodelist()
{
    NODE *p = head;
    while(head)
    {
        p = head;
        head = head->next;
        delete(p);
    }
}
template 
void nodelist:: clearlist()
{
    NODE *p = head;
    while(head)
    {
        p = head;
        head = head->next;
        delete(p);
    }
}

template 
int nodelist::listlength()
{
    int length=0;
    NODE *p=head;
    while(p)
    {
        length++;
        p = p->next;
    }
    return length;
}

template 
void nodelist::pushback(T data)
{
    NODE *p=head;
    NODE *s=new NODE;
    //s=(NODE*)new (NODE);
    if(head==NULL)
    {
        s->data=data;
        s->next=p;
        head=s;
    }
    else
    {
        while(p->next!=NULL)
        {
            p = p->next;
        }
        s->data=data;
        s->next=p->next;
        p->next=s;
    }

}

template 
void nodelist::printlist()
{
    NODE *p = head;
    while(p)
    {
        std::cout<data<<" ";
        p = p->next;
    }
}

template 
void nodelist::searchlist(T data)
{
    int num = 0;
    int flag = 0;
    NODE *p=head;
    while(p)
    {
        if(p->data==data)
        {
            std::cout<<"在链表第 "<next;
        num++;
    }
    if(flag==0)
        std::cout<<"链表中未出现该数据"<

main.cpp

#include 
#include "list.h"
using namespace std;

int main()
{
    nodelist list;
    list.pushback('a');
    list.pushback('s');
    list.pushback('d');
    list.printlist();
    cout<

运行结果:

带模板类的C++链表_第1张图片

注:C和C++在结构体定义上有区别

你可能感兴趣的:(C/C++)