数据结构链表C++实现

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
template<class ElemType>
class linklist
{
public:
    linklist();    //构造函数
    ~linklist();   //析构函数
    bool insert(int pos, ElemType e); //在pos位置插入e
    bool del(int pos, ElemType &e);   //在pos位置删除元素,用e返回
    bool del(int pos);   //在pos位置删除元素,用e返回
    bool empty() const;               //判断链表是否为空
    int  length() const;              //返回链表的长度
    ElemType& operator[] (int index) throw(out_of_range);//返回index位置的值
private:
    class node
    {
    public:
        ElemType data;       //数据域
        node *next;      //指针域
    };
    node *head;
};
template<class ElemType>
linklist<ElemType>::linklist()
{
    head = new node();
    head -> next = NULL;
}
template<class ElemType>
linklist<ElemType>::~linklist()
{
    node *q;
    while(head->next != NULL)
    {
        q = head -> next;
        head -> next = q -> next;
        delete q;
    }
    delete head;
}
template<class ElemType>
bool linklist<ElemType>::insert(int pos, ElemType e)
{
    node *p;
    node *q = new node;
    q -> data = e;
    p = head;
    if(pos < 1)
        return false;
    for(int i = 1; i < pos; ++i)
    {
        if(p -> next != NULL)
 p = p -> next;
        else
            return false;
    }
    q -> next = p -> next;
    p -> next = q;
    return true;
}
template<class ElemType>
bool linklist<ElemType>::del(int pos, ElemType &e)
{
    node *p, *q;
    p = head;
    if(pos < 1)
        return false;
    for(int i = 1; i < pos; ++i)
    {
        if(p -> next != NULL)
            p = p -> next;
        else
            return false;
    }
    if(p -> next -> next == NULL)
    {
        delete p -> next;
        p -> next = NULL;
    }
    else
    {
        q = p -> next;
        p -> next = q -> next;
        delete q;
    }
    return true;
}
template<class ElemType>
bool linklist<ElemType>::del(int pos)
{
    ElemType e;
    del(pos, e);
}
template<class ElemType>
bool linklist<ElemType>::empty() const
{
    return head -> next == NULL;
}
template<class ElemType>
int  linklist<ElemType>::length() const
{
    node *p = head;
    int len = 0;
    while(p -> next)
    {
        ++len;
        p = p -> next;
    }
    return len;
}
template<class ElemType>
ElemType& linklist<ElemType>::operator[] (int index) throw(out_of_range)
{
    if (index < 1 || index > length())
    {
        throw out_of_range("out of range"); //超出范围跑出异常
    }
    node *p;
    p = head;
    for(int i = 0; i < index; ++i)
        p = p -> next;
    return p -> data;
}
int main()
{
    return 0;
}

转载于:https://my.oschina.net/u/196018/blog/383791

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值