链表

#include <iostream>
using namespace std;
template<class T>
struct node
{
    T data[];
    node<T> *next;//
};
template<class T>
class linklist
{
public:
    linklist();               //建立只有头结点的空链表
    linklist(T a[],int n);    //建立有n个元素的单链表
    ~linklist();
    int lengh();
    T get(int i);        //按位置查找
    int locate(T x);     //按值查找元素
    void seek(int i,T x);   //i是位置(插入)     x是值
    T Delete(int i);
    void printlist();
private:
    node<T> *first;      //单链表的头指针
}
template <class T>
linklist<T>::linklist()
{
    first=new node;      //生成头结点
    first->next=NULL;    //头结点的指针域为空
}
template <class T>
linklist<T>::linklist(T a[],int n)      //建立有n个元素的单链表(头插法)
{
    first=new node;
    first->next=NULL;    //初始化一个空链表
    for(int i=0; i<n; i++)
    {
        s=new node;
        s->data=a[i];
        s->next=first->next;
        first->next=s;
    }
}
template <class T>
linklist<T>::linklist(T a[],int n)      //wei
{
    first=new node;
    r=first;
    for(int i=0; i<n; i++)
    {
        s=new node;
        s->data=a[i];
        r->next=s;
        r=s;
    }
}
template <class T>
void linklist<T>::printlist()
{
    p=first->next;//
    while(p!=NULL)
    {
        cout<<p->data;
        p=p->next;
    }
}
template<class T>
int linklist<T>::lengh()
{
    int c=0;
    p=first->next;
    while(p!=NULL)
    {
        p=p->next;//
        c++;
    }
    return c;
}
template<class T>
T linklist<T>::locate(T e)
{
    p=firt->next;
    c=1;
    while(p!=NULL)
    {
        if(e==p->data)
            return c;
        p=p->next;
        cout++;
    }
    return 0;
}
template<class T>
T linklist<T>::get(int i)
{
    p=firt->next;
    c=1;
    while(p!NULL&&c<i)//i=0
    {
        p=p->next;
        cout++;
    }
    if(p==NULL)
        throw "位置";
    else
        return p->data;
}
template<class T>
void linklist<T>::insert(int i,T x)
{
    p=first->next;
    int c=1;
    while(p!=NULL&&c<i)
    {
        p=p->next;
        c++;
    }
    if(p==NULL)
        throw "位置";
    else
    {
        s=new node;
        s->data=x;
        s->next=p->next;
        p->next=s; //*******insert
    }
}
template<class T>
T linklist<T>::Delete(int i)
{
    p=first->next;
    int c=0;
    while(p!=NULL&&c<i-1)
    {
        p=p->next;
        c++;
    }
    if(p==NULL||p->next==NULL)
        throw "位置";
    else
    {
        q=p->next;
        x=q->data;//
        p->next=q->next;
        delete q;
        return x;//返回被删元素值
    }
}
template <class T>
linklist<T>::~linklist()
{
    while(first!=NULL)
    {
        q=first;
        first=first->next;
        delete q;
    }
}
int main()
{
    cout << "Hello world!" << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值