由于最近工作需求,自封装的链表,代码:
#include <stdio.h>
#include <stdexcept>
#include <exception>
#include <iostream>
using namespace std;
struct timer_list
{
int type;
timeval tval;
// tv_sec;
// tv_usec;
void(*function)(unsigned long); //timer超时回调函数
unsigned long data; //传递给回调函数的数据,也就是定时器数据
};
typedef timer_list T;
class List
{
private:
struct Node
{ //内部类
T data;
Node* next;
Node(T& d):data(d),next(){}
};
Node *head; //头指针
int sz; //元素个数
Node*& getptr(int pos)
{
Node* p = head;
if(pos == 0)
{
return head;
}
for(int i=0;i<pos-1;++i)
{
p = p->next;
}
return p->next;
}
public:
List(void):head(NULL),sz(0){}
~List(){clear();}
//向链表中插入一个元素
bool insert(T& d)
{
return insert(sz,d);
}
// //打印链表
// void travel(void)
// {
// Node* p = head;
// while(p)
// {
// cout << p->data << ' ';
// p = p->next;
// }
// cout << endl;
// }
//在指定位置增加元素
bool insert(int pos, T& d)
{
if(pos < 0 || pos > sz)
{
return false;
}
Node*& r = getptr(pos);
Node* pn = new Node(d);
pn->next = r;
r = pn;
sz++;
return true;
}
//清空链表
void clear(void)
{
Node* p = head;
while(head)
{
head = head->next;
delete p;
p = head;
}
sz = 0;
}
//删除节点
bool erase(int pos)
{
if(pos < 0 || pos >= sz)
{
return false;
}
Node*& r = getptr(pos);
Node* q = r;
r = r->next;
delete q;
sz--;
return true;
}
T& at(int pos)throw(out_of_range)
{
if(pos < 0 || pos >= sz)
{
throw out_of_range("out");
}
Node*& r = getptr(pos);
return r->data;
}
int size(void)
{
return sz;
}
//返回最后一个元素
T& back(void)
{
return at(sz-1);
}
//返回第一个元素
T& front(void)
{
return at(0);
}
//判空
bool empty(void)
{
return (sz == 0);
}
//在链表尾插入元素
void push_back(T& d)
{
insert(sz,d);
}
//在链表首插入元素
void push_front(T& d)
{
insert(0,d);
}
void pop_back(void)
{
erase(sz-1);
}
void pop_front(void)
{
erase(0);
}
};